Running Java code in R
Let’s say you have a Java class StringTest
package somepackage;
public class StringTest {
public String changeString(String str) {
return "I have changed the string: " + str;
}
}
inside file
src
`-- somepackage
`-- StringTest.java
and you want to run it in R. All you have to do is to compile the code.
> javac -d target src/somepackage/StringTest.java
You will get compiled version of your class – it will have class extension.
target
`-- somepackage
`-- StringTest.class
This is the class you want to run. Let’s take a look at R.
> R
R version 3.5.2 (2018-12-20) -- "Eggshell Igloo"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin15.6.0 (64-bit)
...
...
> # if you don't have rJava installed yet, install it
> install.packages("rJava")
...
...
> library(rJava)
> # initialize Java environment
> .jinit()
>
> # we have to tell rJava where to look for our class
> .jaddClassPath(paste(getwd(),"/target", sep = ""))
>
> # we can create instance of our class
> obj <- .jnew("somepackage/StringTest")
>
> # and call the method with arguments
> result <- .jcall(obj, returnSig="Ljava/lang/String;", method="changeString", "Hello world!")
> result
[1] "I have changed the string: Hello world!"
>
Sometimes, it’s hard to say what is the signature of methods (e.g. it may have lots of arguments, strange return type). You can easily find the signature using javap.
> javap -cp target somepackage.StringTest
Compiled from "StringTest.java"
public class somepackage.StringTest {
public somepackage.StringTest();
public java.lang.String changeString(java.lang.String);
}
In case you have issues while installing rJava on macOS, make sure to take a look here: R 3.4, rJava, macOS and even more mess ;) and here: R, Java, rJava and macOS adventures.