JRuby中調(diào)用java帶可變參數(shù)的方法
Posted on 2008-06-14 22:39 dennis 閱讀(2185) 評論(1) 編輯 收藏 所屬分類: 動態(tài)語言 今天同事遇到的問題,用JRuby調(diào)用一個java方法,該方法使用了jdk1.5的可變參數(shù)。我一開始以為只要簡單地將可變參數(shù)表示為數(shù)組即可,例如下面的兩個java類:
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中調(diào)用Test的hello方法,該方法有個可變參數(shù)args。所謂可變參數(shù)經(jīng)過編譯后其實也就是數(shù)組,這個可以通過觀察字節(jié)碼知道,那么如果用數(shù)組來調(diào)用可以不?public void echo(String name){
System.out.println(name);
}
}
public class Test{
public void hello(String name,Echo

System.out.println("hello,"+name);
for(Echo e:args){
e.echo(name);
}
}
}
require 'java'
require 'test.jar'
include_class 'Test'
include_class 'Echo'
t.hello("dennis") #報錯,參數(shù)不匹配
t.hello("dennis",[]) #報錯,類型不匹配
很遺憾,這樣調(diào)用是錯誤的,原因如上面的注釋。具體到類型不匹配,本質(zhì)的原因是JRuby中的數(shù)組與java中對數(shù)組的字節(jié)碼表示是不一致的,JRuby中的數(shù)組是用org.jruby.RubyArray類來表示,而hello方法需要的數(shù)組卻是是[LEcho。解決的辦法就是將JRuby的數(shù)組轉(zhuǎn)成java需要的類型,通過to_java方法,因而下面的調(diào)用才是正確的,盡管顯的麻煩:require 'test.jar'
include_class 'Test'
include_class 'Echo'
t.hello("dennis") #報錯,參數(shù)不匹配
t.hello("dennis",[]) #報錯,類型不匹配
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"))
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"))