Search code examples
javarexceptionrjava

NoSuchMethodError: <init> when using rJava to create a new object


Recently I came across a problem when using rJava. First I create a public class DirectedEdge:

public class DirectedEdge {
    public int v;
    public int w;
    public double weight;
    public DirectedEdge(){}
    public DirectedEdge(int v, int w, double weight) {
        this.v = v;
        this.w = w;
        this.weight = weight;
    }
}

Then I run the following codes on RStudio:

.jinit();
.jaddclassPath('XXXXXX');
.jnew('DirectedEdge');
.jnew('DirectedEdge',1,2,0.1);

I have already set the classpath to where my .class files are located, but the third line did run and the forth line failed. RStudio gave me an exception:

Error in .jnew("DirectedEdge", 1, 2, 0.1) : java.lang.NoSuchMethodError: <init>

I also tried the example in rJava document:

.jnew('java/lang/String',"Hello World!")

It worked well. So what's the problem? Thanks a lot.


Solution

  • The default type of the number is double, so use .jnew("DirectedEdge", as.integer(1), as.integer(2), 0.1) instead