Running JAR file from R using rJava (without spawning new process)

Let’s say we have this, very simple, structure of the project

.
|-- Manifest.txt
`-- src
    `-- somepackage
        `-- StringTest.java

where StringTest.java is a very simple Java class

package somepackage;

public class StringTest {
  public String changeString(String str) {
    return "I have changed the string: " + str;
  }

  public static void main(String [] arg) {
    System.out.println(new StringTest().changeString("Hello"));
  }
}

while Manifest.txt contains

Manifest-Version: 1.0
Main-Class: somepackage.StringTest

We can easily create JAR (“executable”) from these files using jar application

# create JAR
> jar cfm test.jar Manifest.txt -C target somepackage/StringTest.class

# execute JAR
> java -jar test.jar
I have changed the string: Hello

Now, let’s try to run this code inside R. It’s quite straightforward.

# make sure R will be able to pick it up
> export CLASSPATH=./test.jar
> R

R version 3.6.1 (2019-07-05) -- "Action of the Toes"
Copyright (C) 2019 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin15.6.0 (64-bit)

...
...
...

> library(rJava)
> .jinit()
> obj <- .jnew("somepackage.StringTest")
> s <- .jcall(obj, returnSig="V", method="main", c("Hello", "Hello") )
I have changed the string: Hello
>