1

I'm new to Ruby & Jruby . I want to test some stuffs of jruby in java code

Here is my code :

import java.util.ArrayList;
import java.util.HashMap;
import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.ScriptingContainer;

public class Test {
    public static void main(String[] args){
        ScriptingContainer container = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
        Test t = new Test();
        LogStatBean bean = t.new LogStatBean();
        container.setHomeDirectory("classpath:/META-INF/jruby.home");
        container.put("bean", bean);
        container.runScriptlet("arr = [1, 2, 3, 4, 5, 6]");
        container.runScriptlet("puts arr");
        container.runScriptlet("bean.setOutput(arr) ");
        System.out.println(bean.getOutput());

    }
    public class LogStatBean {
        public ArrayList<HashMap<String, Object>> getOutput() {
            return output;
        }
        public void setOutput(ArrayList<HashMap<String, Object>> output) {
            this.output = output;
        }
        public ArrayList<HashMap<String, Object>> output;

    }
}

I cannot set the java local variable with type ArrayList in jruby ,it raise an error

TypeError: cannot convert instance of class org.jruby.RubyArray to class java.util.ArrayList
  (root) at <script>:1

What i have to do ?

1 Answer 1

1

array in Ruby (usually) converts to a Java array - so either stop expecting an ArrayList or do the conversion yourself in Ruby ... this piece of Ruby should be helpful :

>> [1, 2, 3].class
=> Array
>> [1, 2, 3].to_java.java_class
=> class [Ljava.lang.Object;
>> [1, 2, 3].to_java('java.lang.Integer').java_class
=> class [Ljava.lang.Integer;
>> java.util.ArrayList.new [1, 2, 3]
=> #<Java::JavaUtil::ArrayList:0x1b802d73>
>> java.util.Arrays.asList([1, 2, 3].to_java)
=> #<Java::JavaUtil::Arrays::ArrayList:0x10478ebc>
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.