2

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.

1 Answer 1

1

First, notice that by putting MyJavaClass.class as a ruby variable, the Java Class object available is made available to your JRuby script. The following works:

java_class = MyJavaClass.getDeclaredConstructor(java.lang.String.java_class)
someInstance = java_class.new_instance("Joe")

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 MyJavaClass is on the classpath (or ruby $LOAD_PATH). Then, call the class as follows in Test.rb.

someInstance = Java::MyJavaClass.new("joe")

or

 java_import 'MyJavaClass'
 someInstance = MyJavaClass.new("Joe")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.