The problem that colleagues encounter today is to call a Java method with JRuby, which uses the jdk1.5 variable parameters. I thought it would be simple to represent a variable parameter as an array, such as the following two Java classes:
public class Echo{
public void echo(String name){
System.out.println(name);
}
}
public class Test{
public void hello(String name,Echoargs){
System.out.println("hello,"+name);
for(Echo e:args){
e.echo(name);
}
}
}
I want to call the Hello method of test in JRuby, which has a variable parameter args. The so-called variable parameters are compiled in fact the array, which can be observed by the byte code, so if the array to call can not?
Require ' Java '
Require ' Test.jar '
Include_class ' Test '
Include_class ' Echo '
T.hello ("Dennis") #报错, parameters do not match
T.hello ("Dennis", []) #报错, type mismatch Unfortunately, this call is wrong, for reasons such as the above comment. Specific to type mismatch, the intrinsic reason is that the array in JRuby is inconsistent with the byte-code representation of the arrays in Java, the array in JRuby is represented by the Org.jruby.RubyArray class, and the array of the Hello method requires is [Lecho. The solution is to convert the JRuby array to the Java-required type, through the To_java method, so the following call is correct, despite the obvious trouble:
require 'java'
require 'test.jar'
include_class 'Test'
include_class 'Echo'
t=Test.new
t.hello("dennis",[].to_java("Echo"))
e1=Echo.new
t.hello("dennis",[e1].to_java("Echo"))
e2=Echo.new
t.hello("dennis",[e1,e2].to_java("Echo"))