简体   繁体   English

显式重写Jruby中的Java方法?

[英]explicitly override a Java method in Jruby?

Is there an explicit way to override a Java method in JRuby-subclass? 有没有一种明确的方法可以覆盖JRuby子类中的Java方法?

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

In a Java I'd use @override to make subclassing explicit. 在Java中,我将使用@override使子类显式化。

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: 当我在Jruby中覆盖此内容时,我想要这样的内容:

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. 似乎可以避免由于仅依赖于方法命名而在Java集成中遇到一些难以跟踪的错误。

(Actually I find it would be handy in Ruby generally too, to a lesser extent..) (实际上,在较小的程度上,我发现它通常也可以在Ruby中使用。)

UPDATE: now packed into gem 'overrides' https://github.com/kares/overrides 更新:现在包装成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 : 通过一些元编程,这可以与Ruby方法一起使用(并且可以与JRuby一起使用,因为Java继承的方法显示为Ruby方法)...我将其总结如下:

https://gist.github.com/kares/7434811 ... now that someone finds it useful might put it in a gem :) https://gist.github.com/kares/7434811 ...现在有人发现它很有用,可能会将其放入宝石中:)

usage sample (NOTE: you do not need to hook it up for all classes/modules) JRuby style : 使用示例(注意:您不需要为所有类/模块都将其连接起来)JRuby style:

Object.extend Override

class JList < java.util.ArrayList

  override
  def trim_to_size; super; end

  def isEmpty; false; end

  override :isEmpty

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM