庄周梦蝶

生活、程序、未来
   :: 首页 ::  ::  :: 聚合  :: 管理

JRuby中调用java带可变参数的方法

Posted on 2008-06-14 22:39 dennis 阅读(2168) 评论(1)  编辑  收藏 所属分类: 动态语言
    今天同事遇到的问题,用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,Echoargs){
        System.out.println(
"hello,"+name);
        
for(Echo e:args){
            e.echo(name);
        }
    }
}
   我想在jruby中调用Test的hello方法,该方法有个可变参数args。所谓可变参数经过编译后其实也就是数组,这个可以通过观察字节码知道,那么如果用数组来调用可以不?
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 '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"))



评论

# re: JRuby中调用java带可变参数的方法  回复  更多评论   

2008-06-17 14:10 by dennis
@Jack.Wang
如果我回骂的话,那还真把你当人看了

只有注册用户登录后才能发表评论。


网站导航: