将@Deprecated 注释添加到超类、子类或两者?

Add @Deprecated annotation to the superclass, subclasses or both?

我想弃用特定方法。此方法现在需要一个新参数,但我想保留以前的实现以实现向后兼容性。

我应该只在超类(在 library-api 项目中)、子类(在 library-impl 项目中)或两者上添加 @Deprecated 注释吗?

任何使用或引用 Deprecated 方法的方法都会生成编译器警告,除非它本身是 Deprecated(或者它具有适当的 @SuppressWarnings("deprecation"))。

因此,您应该在超类和子类上设置 @Deprecated 注释(如 Sajan 所评论的)。您还需要使用这些方法将其递归地添加到其他方法中。

另请注意 Rinke 在他的回答中的好评:

The @Deprecated annotation is not annotated with @Inherited. The annotation will therefore not automatically apply to the inherited method.

背后的逻辑是所有使用一些已弃用代码的东西(=不再是正确的做法,将在不久的将来被删除),也应标记为“不再是正确的做法,将在不久的将来删除”。

如果您要弃用的方法的行为(代码)用于有用的(未弃用的)方法,您应该将代码提取到另一个函数中由我们的其他有效代码调用。

而不是:

@Deprecated
public void someMethodWithBadSignature() {
   //some Code
}
public void otherValidMethod() {
    someMethodWithBadSignature();  /// <====== WARNING
}

使用:

@Deprecated
public void someMethodWithBadSignature() {
   someMethodsCode();
}
private void someMethodCode() {
    //your original code
}
public void otherValidMethod() {
    someMethodCode();
}

@Deprecated annotation is not annotated with @Inherited。因此注释不会自动应用于继承的方法。

这不一定是个问题,因为通常 IDEs 会检查声明的类型。因此,如果您在 superclass/interface 上弃用该方法,即使您使用未明确弃用该方法的 subclass/implementation,IDE 也会抱怨。我的意思是:

SomeType x = new Abc();   // where Abc is an implementation or subclass of SomeType
x.doSomething();   // IDE should still complain if SomeType#doSomething() is deprecated

如果您使用 implementor/subclass 而不是 interface/superclass 进行类型声明,那么您可能需要在 implementing/overriding 方法上添加一个 @Deprecated 注释。不过,很大程度上取决于代码分析器。理论上它仍然可以检查 interface/superclass 上的弃用,即使您不将它用于类型声明。

Abc x = new Abc();
x.doSomething();   // here you're on your own if Abc#doSomething() is not deprecated