Search code examples
rjava

rJava: calling a Java function to retrieve a list of objects


I need to get in R a list of objects from Java. In the code below I succeeded in getting the list in R (the length of the list is correct) but I cannot see the objects content.

This class represents the objects:

package mypackage;
public class ValueObject 
    public String s;
    public int i;
}

This class returns the list of objects:

package mypackage;
public class MyClass {

    public ValueObject [] test(){

        ValueObject [] array = new ValueObject [3];

        ValueObject a = new ValueObject();
        a.i = 1;
        a.s = "A";
        array[0] = a;

        ValueObject b = new ValueObject();
        b.i = 2;
        b.s = "B";
        array[1] = b;

        ValueObject c = new ValueObject();
        c.i = 3;
        c.s = "C";
        array[2] = c;

        return array;
    }
}    

And I run it in R, like so:

obj = .jnew("mypackage/MyClass")
x = .jcall(obj,"[Lmypackage/ValueObject;","test")

print(length(x)) shows 3, meaning that the objects are there. But I can't figure out how to access the data in the objects. I tried:

x[1]$s
x[1]["s"]
x[1]@s

and always get NULL. what's wrong with this code?


Solution

  • this does the trick:

    print(x[[1]]$s)