简体   繁体   English

Java注释,用于不调用重写的方法

[英]java annotation for do not invoke overridden method

I have two classes Foo and Bar, where Bar extends Foo. 我有Foo和Bar两个类,其中Bar扩展了Foo。

In the superclass, there is a method f(). 在超类中,有一个方法f()。 The subclass overrides this method and purposefully throws an exception so that f() is never invoked on instances of Bar. 子类重写此方法,并有意引发异常,以便从不对Bar实例调用f()。

class Foo {
  public void f() {
     // does something useful
  }

}


class Bar extends Foo {
  @Override
  public void f() {
      throw new UnsupportedOperationException("Srsly, thou shalt not");
  }
}

Now here is my question: is there some annotation that I can use on the overridden method that communicates to IDEs such as Eclipse that one shouldn't call it? 现在是我的问题:在与Eclipse之类的IDE进行通信的重写方法上是否可以使用一些注解,而该注解是不应调用的? I found myself wanting to lightly-abuse the @deprecated tag so that the auto-complete list in Eclipse crosses the method out when the user is dealing with an instance of Bar, but I wanted to know if there was a better option. 我发现自己想轻度滥用@deprecated标记,以便当用户处理Bar实例时,Eclipse中的自动完成列表 将方法删除 ,但是我想知道是否有更好的选择。

class Bar extends Foo {

  /**
   * @deprecated
   */
  @Override
  public void f() {
      throw new UnsupportedOperationException("Srsly, thou shalt not");
  }
}

No not really as all (non static) methods in Java are virtual and the calls are resolved at runtime. 并非完全如此,因为Java中的所有(非静态)方法都是虚拟的,并且调用在运行时已解决。 In other words, there's no way for the compiler to detect that Bar's version of the method will be called in runtime. 换句话说,编译器无法检测到将在运行时调用Bar的方法版本。

I would make the function f() private. 我会将函数f()设为私有。 That way, it can never be called outside Bar. 这样,就永远不能在Bar外调用它。

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

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