在 JRuby 中重写重载的 Java 方法
假设我有一个如下所示的 Java 类:
public class MyClass {
public void doSomething(Object o1) { }
public void doSomething(Object o1, Object o2) {}
}
请注意,有两个具有不同参数的 doSomething
方法。
在 JRuby 中,我如何子类化此类并为每个 doSomething
提供实现?有没有办法在 Java 中添加一个 shim 类来简单地将方法调用路由到具有明确名称的 ruby 方法?
谢谢!
Let's say I have a Java class like this:
public class MyClass {
public void doSomething(Object o1) { }
public void doSomething(Object o1, Object o2) {}
}
Note that there are two doSomething
methods with different arities.
In JRuby, how can I sub-class this class and provide implementations for each arity of doSomething
? Is there a way to do this short of adding a shim class in Java that simply routes method calls to ruby methods with unambiguous names?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Ruby 中,同一个类中不能有多个同名方法。但是,您可能有一个带有可变参数的方法,并根据参数的数量进行调度,请查看这篇文章:http: //rubylearning.com/satishtalim/ruby_overloading_methods.html
连同 Dave Newton 的参考,这是正确的解决方案。 JRuby 将所有同名的 Java 方法路由到一个 Ruby 方法。您可以从那里随意发送。因此,在这种情况下,以下 Ruby 就足够了:
In Ruby you can't have more that one method with the same name, in the same class. However, you may have a method with variable arguments and dispatch depending on the number of arguments, check this article: http://rubylearning.com/satishtalim/ruby_overloading_methods.html
Along with Dave Newton's reference, this is the correct solution. JRuby routes all Java methods with the same name to one Ruby method. You can dispatch as you like from there. So in this case, the following Ruby is sufficient:
请参阅 https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby
特别是,查看
java_send
,您可以使用它指定要调用哪个Java 方法。See https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby
In particular, look at
java_send
, with which you can specify which Java method to call.