当前位置:首页 > 网络编程 > 软件语言 > JAVA > JRuby中调用java带可变参数的方法

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

点击次数:22 次 发布日期:2008-12-12 13:10:43 作者:源代码网
源代码网推荐 本文将讲述在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,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"))

[作者:dennis]

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华