Dave Ray
Dave Ray

Reputation: 40005

Overriding overloaded Java methods in JRuby

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!

Upvotes: 1

Views: 1354

Answers (2)

Óscar López
Óscar López

Reputation: 236004

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

Upvotes: 1

banzaiman
banzaiman

Reputation: 2663

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

Upvotes: 1

Related Questions