我是Ruby&的新手Jruby。我想在java代码中测试一些jruby的东西
这是我的代码:
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;
}
}
我无法在jruby中设置类型为ArrayList的java局部变量,它会引发错误
TypeError: cannot convert instance of class org.jruby.RubyArray to class java.util.ArrayList
(root) at <script>:1
我该怎么做?
答案 0 :(得分:0)
数组(通常)转换为Java数组 - 所以要么停止期待一个ArrayList,要么自己在Ruby中进行转换......这段Ruby应该会有所帮助:
>> [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>