开发者

Overriding overloaded Java methods in JRuby

开发者 https://www.devze.com 2023-04-11 02:57 出处:网络
Let\'s say I have a Java class like this: public class MyClass { public void doSomething(Object o1) { }

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 开发者_C百科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!


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号