同事遇到用 JRuby 呼叫 Java 可變參數方法的問題。該方法使用 JDK 1.5 可變參數特性。起初以為將可變參數表示為陣列即可,例如:
public class Echo {
public void echo(String name) { System.out.println(name); }
}
public class Test {
public void hello(String name, Echo... args) {
System.out.println("hello," + name);
for(Echo e : args) { e.echo(name); }
}
}
在 JRuby 中呼叫 Test.hello,嘗試用陣列:
require 'java'
require 'test.jar'
include_class 'Test'
include_class 'Echo'
t = Test.new
t.hello("dennis") # 錯誤:參數不匹配
t.hello("dennis", []) # 錯誤:型別不匹配
原因:JRuby 陣列以 org.jruby.RubyArray 表示,而 Java 方法需要 [LEcho(Echo 陣列),型別不一致。
將 JRuby 陣列轉換為 Java 需要的型別,使用 to_java 方法:
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"))
雖然顯得麻煩,但這是正確呼叫方式。to_java("Echo") 將 Ruby 陣列轉換為 Java 的 Echo[] 型別。