JRuby中调用java带可变参数的方法
今天同事遇到的问题,用JRuby调用一个java方法,该方法使用了jdk1.5的可变参数。我一开始以为只要简单地将可变参数表示为数组即可,例如下面的两个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中调用Test的hello方法,该方法有个可变参数args。所谓可变参数经过编译后其实也就是数组,这个可以通过观察字节码知道,那么如果用数组来调用可以不?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") #报错,参数不匹配
t.hello("dennis",[]) #报错,类型不匹配
很遗憾,这样调用是错误的,原因如上面的注释。具体到类型不匹配,本质的原因是JRuby中的数组与java中对数组的字节码表示是不一致的,JRuby中的数组是用org.jruby.RubyArray类来表示,而hello方法需要的数组却是是[LEcho。解决的办法就是将JRuby的数组转成java需要的类型,通过to_java方法,因而下面的调用才是正确的,尽管显的麻烦:require 'test.jar'
include_class 'Test'
include_class 'Echo'
t.hello("dennis") #报错,参数不匹配
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"))
文章转自庄周梦蝶 ,原文发布时间2008-06-14
最后更新:2017-05-17 18:01:58