考虑以下简化的接口(interface)继承层次结构:
// Starting point:
public interface Base {
void Foo();
}
public interface Derived extends Base {
}
目的是将Foo
方法从Base
接口(interface)移动到Derived
接口(interface):
// Desired end-point:
public interface Base {
}
public interface Derived extends Base {
void Foo();
}
为了分阶段实现此重大更改,需要在一段时间内保留 Base
接口(interface)的向后兼容性。
这可以通过将 Base
接口(interface)上的方法标记为 @Deprecated
来实现:
// Intermediate state:
public interface Base {
/**
* @deprecated This method is deprecated as of release X. Derived.Foo should be used instead.
*/
@Deprecated void Foo();
}
public interface Derived extends Base {
void Foo();
}
当我编译这段代码时,我收到一条关于Derived
的编译器警告:
[deprecation] Foo() in interface Base has been deprecated
奇怪的是,如果我从 Base
中的文档中删除 @deprecated
(但保留 @Deprecated),此警告就会消失。
我收到此警告是否正确?如果是,我该如何解决?
警告似乎表明 Derived.Foo
正在“使用”Base.Foo
(已弃用)。但是 Derived.Foo
“使用”已弃用的 Base.Foo
的唯一能力是覆盖它。这似乎是说不允许在派生方法中覆盖已弃用的接口(interface)方法。
如果是这种情况,我是否应该用 @SuppressWarnings("deprecation")
装饰 Derived
以抑制警告?
最佳答案
我相信您的要求是有效的,我毫不怀疑覆盖已弃用的方法是正确的方法。
我认为@deprecated 和@Deprecated 之间的区别主要是历史原因。 @Deprecated 是 java 5 中的官方方式,但它是新的,因此我们希望将其与 @deprecated 一起使用。
另请注意,遗憾的是,@Deprecated 不允许您指定信息......虽然通常需要信息,例如告诉应该使用什么作为替代品,或者何时期望完全删除弃用的方法.
不知道更多,并且知道只要有效地删除 super 方法问题就会消失,我会使用@SuppressWarnings("deprecation"),可能带有评论让你的继任者理解......(和另一个评论 super 方法,告诉他们在删除方法时删除所有内容)。 ;-)
关于Java:如何在覆盖已弃用成员的派生接口(interface)中避免弃用警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1213362/