有一个带有重载方法的 Java 类:
public void test(float x) {
}
public void test(RubyArray array) {
}
在 ruby 中,
object.test(1.0)
工作正常。然而:
object.test([1.0,2.0])
将崩溃并显示消息:
org.jruby.exceptions.RaiseException: (NameError) no method 'test' for arguments (org.jruby.RubyArray) on Java::MyNamespace::MyClass
available overloads:
(org.jruby.RubyArray)
(int)
但是,如您所见,这没有任何意义。它告诉我,我的 RubyArray
类型的参数没有方法。 ,然后它立即告诉我类型为 RubyArray
的参数有一个可用的重载.
有趣的是,如果您删除 (int)
,这会正常工作重载,也就是说,如果接受 RubyArray
的方法有效没有其他重载。
我已经创建了许多重载的 Java 方法并在 Ruby 中使用过它们,所以我猜测问题主要与 RubyArray
有关。论点本身 - 虽然我没有看到问题。
这是为什么呢?我在这里做错了什么?
我正在使用 JRuby 1.7.11
, 为我认为的建筑 Java SE 6
在 Eclipse Kepler for Mac 上。
为了方便测试,可以运行以下两个程序:
这个有效:
import javax.script.*;
import org.jruby.RubyArray;
public class Main {
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
Main app = new Main();
}
public Main() throws ScriptException, NoSuchMethodException {
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
jruby.eval("include Java;\n" + "def start(main) main.test([1,2,3]); end");
Invocable invocable = (Invocable)jruby;
invocable.invokeFunction("start",this);
}
public void test(RubyArray array) {
System.out.println(array);
}
}
这行不通:
import javax.script.*;
import org.jruby.RubyArray;
public class Main {
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
Main app = new Main();
}
public Main() throws ScriptException, NoSuchMethodException {
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
jruby.eval("include Java;\n" + "def start(main) main.test([1,2,3]); end");
Invocable invocable = (Invocable)jruby;
invocable.invokeFunction("start",this);
}
public void test(int x) {
System.out.println(x);
}
public void test(RubyArray array) {
System.out.println(array);
}
}
最佳答案
我认为这是因为在 Ruby 中你不能重载具有相同数量参数的方法,因为没有数据类型声明。您只能使用不同数量的参数重载方法:public void test(int x)
vs public void test(RubyArray arr, int x)
因此,当您调用测试方法时,它会翻转并只采用第一种方法(不知道它如何或为何搜索或找到具有 int 参数的方法)。
关于java - 为什么 JRuby 在重载时不能使用我的参数是 RubyArray 的 Java 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23121703/