package rjava jcall error in R

3.2k views Asked by At

I want to use R to input a parameter into Java, for example "1000". Then method of StringToNum process and output its return to R,namely 1000. Seems it is the work of .jcall(), but I dont know how to do with its parameters.As I dont know Java, Could you please help me? Thank you very much!

Java code

package com.mingdong.rcalljava.test;

import java.io.PrintStream;

public class StringToNum
{
 private String inputString = null;

 public StringToNum(String inputString)
{
  this.inputString = inputString;
}

 public StringToNum()
{
}

 public int convertStringToInt() 
{
    if (this.inputString == null) {
    this.inputString = "100";
    }
    return Integer.valueOf(this.inputString).intValue();
}

 public static void main(String[] args)
  {
   StringToNum stringToNum = new StringToNum();
   int num = stringToNum.convertStringToInt();
   System.out.println("num:" + num);
  }
 }

R code

library(rJava)
.jinit()
.jinit('D:/Eclipse/dailyjob/javaProject/TestRCallJava.jar')

## .jaddClassPath("D:\\Eclipse\\dailyjob\\javaProject\\TestRCallJava.jar")

inputString <- .jnew("java.lang.String","1000")
inputString %instanceof% "java.lang.String"

StringToNum <- .jnew("com.mingdong.rcalljava.test.StringToNum")
StringToNum %instanceof% "com.mingdong.rcalljava.test.StringToNum"

.jcall(StringToNum,returnSig= "V", "main",inputString )
Error in .jcall(StringToNum, returnSig = "V", "main") : 
method main with signature ()V not found
1

There are 1 answers

0
Beasterfield On

There are two issues. On the Java side in main you call the constructor new StringToNum() which does not exist. The main method should rather look like:

public static void main( String[] args ) {
  StringToNum stringToNum = new StringToNum( args[0] );
  int num = stringToNum.convertStringToInt();
  System.out.println("num:" + num);
}

Maybe this solves already your problem. However, in general you call static methods in Java not on the object but on the class. If you'd call the main method from Java you'd have to call

StringToNum.main( "1000" );

instead of calling

StringToNum obj = new StringToNum( "" );
obj.main( "1000" );

You should also avoid to call the low-level functions (indicated by starting with a .) of the rJava package. So as indicated in rJava .jcall return type issue the proper call would be

J("com.mingdong.rcalljava.test.StringToNum")$main( "1000" ) # untested