首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

JRuby 呼叫 Java 可變參數方法

     編輯:Java 相關知識

問題背景

同事遇到用 JRuby 呼叫 Java 可變參數方法的問題。該方法使用 JDK 1.5 可變參數特性。起初以為將可變參數表示為陣列即可,例如:

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,嘗試用陣列:

require 'java'
require 'test.jar'
include_class 'Test'
include_class 'Echo'
t = Test.new
t.hello("dennis")           # 錯誤:參數不匹配
t.hello("dennis", [])       # 錯誤:型別不匹配

原因:JRuby 陣列以 org.jruby.RubyArray 表示,而 Java 方法需要 [LEcho(Echo 陣列),型別不一致。

解決方案

將 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"))

雖然顯得麻煩,但這是正確呼叫方式。to_java("Echo") 將 Ruby 陣列轉換為 Java 的 Echo[] 型別。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved