JRuby中調用java帶可變參數的方法

來源:互聯網
上載者:User

今天同事遇到的問題,用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"))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.