explicitly override a Java method in Jruby?

1k Views Asked by At

Is there an explicit way to override a Java method in JRuby-subclass?

public class Yours {
  public String hi() { 
     return "Hello original";
  }
}

In a Java I'd use @override to make subclassing explicit.

public class Mine extends Yours {
  @Override   // throws an error if the above is not a superclass method
  public String hi() { 
     return "Hello override!";
  }
}

When I override this in Jruby, I'd like something like this:

class JRMine < Yours 
   java_overrides     # I wish this was there, making sure "wiring" is ok
   def hi()
     "Hello Jruby"
   end
end

Now, is there any equivalent technique to achieve safe overriding? It seems it could avoid some hard-to-track errors in java integration, due to just relying on method naming.

(Actually I find it would be handy in Ruby generally too, to a lesser extent..)

1

There are 1 best solutions below

2
On

UPDATE: now packed into gem 'overrides' https://github.com/kares/overrides

with a bit of meta-programming this is possible to do with Ruby methods (and works with JRuby since Java inherited methods show up as Ruby ones) ... I've put it up in a gist :

https://gist.github.com/kares/7434811 ... now that someone finds it useful might put it in a gem :)

usage sample (NOTE: you do not need to hook it up for all classes/modules) JRuby style :

Object.extend Override

class JList < java.util.ArrayList

  override
  def trim_to_size; super; end

  def isEmpty; false; end

  override :isEmpty

end