Java code executing a Ruby script:
ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
ruby.put("MyJavaClass", MyJavaClass.class);
ruby.runScriptlet(readFile("Test.rb"));
MyJavaClass code:
public class MyJavaClass {
public MyJavaClass(String name) {
System.out.println("I got a name: " + name);
}
}
Ruby code within Test.rb:
someInstance = MyJavaClass.new("Joe")
This is what I tried to initialize a Java object within a Ruby script using JRuby. It did not work.
First, notice that by putting
MyJavaClass.classas a ruby variable, the Java Class object available is made available to your JRuby script. The following works:It uses Java reflection to instantiate
MyJavaClass.However, this can be done more simply without adding the class as ruby var. First, ensure the path of the folder of
MyJavaClassis on the classpath (or ruby$LOAD_PATH). Then, call the class as follows inTest.rb.or