在 JRuby 中重写重载的 Java 方法

发布于 2024-12-08 14:35:54 字数 349 浏览 5 评论 0原文

假设我有一个如下所示的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撩心不撩汉 2024-12-15 14:35:54

在 Ruby 中,同一个类中不能有多个同名方法。但是,您可能有一个带有可变参数的方法,并根据参数的数量进行调度,请查看这篇文章:http: //rubylearning.com/satishtalim/ruby_overloading_methods.html

连同 Dave Newton 的参考,这是正确的解决方案。 JRuby 将所有同名的 Java 方法路由到一个 Ruby 方法。您可以从那里随意发送。因此,在这种情况下,以下 Ruby 就足够了:

class MyRubyClass < MyClass

  ...

  def doSomething(*args)
    ... do something with args ...
  end
end

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:

class MyRubyClass < MyClass

  ...

  def doSomething(*args)
    ... do something with args ...
  end
end
辞慾 2024-12-15 14:35:54

请参阅 https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby

特别是,查看java_send,您可以使用它指定要调用哪个Java 方法。

obj = MyClass.new
obj.java_send :doSomething, [Java::Object], o1
obj.java_send :doSomething, [Java::Object, Java::Object], o1, o2

See https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby

In particular, look at java_send, with which you can specify which Java method to call.

obj = MyClass.new
obj.java_send :doSomething, [Java::Object], o1
obj.java_send :doSomething, [Java::Object, Java::Object], o1, o2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文