Reputation: 7366
I want to deprecate a specific method. This method now needs a new argument, but I want to keep the previous implementations for backward compatibility.
Should I add the @Deprecated
annotation only on the superclass (in the library-api project), on the subclasses (in the library-impl projects), or both?
Upvotes: 3
Views: 1448
Reputation: 6332
The @Deprecated
annotation is not annotated with @Inherited
. Therefore the annotation will not automatically apply to the inherited methods.
This is not necessarily a problem, since typically IDEs will check against the declared types. So if you deprecate the method on a superclass/interface, the IDE will complain even if you use a subclass/implementation where the method is not explicitly deprecated. I mean the following:
SomeType x = new Abc(); // where Abc is an implementation or subclass of SomeType
x.doSomething(); // IDE should still complain if SomeType#doSomething() is deprecated
If you use the implementor/subclass instead of the interface/superclass for type declaration, then you probably need a @Deprecated
annotation on the implementing/overriding method. A lot depends on the code analyzer though. In theory it could still check for deprecation on the interface/superclass, even if you don't use it for type declaration.
Abc x = new Abc();
x.doSomething(); // here you're on your own if Abc#doSomething() is not deprecated
Upvotes: 3
Reputation: 1100
Any method using or referencing a Deprecated
method will generate a compiler warning, unless it is itself Deprecated
(or it has the appropriate @SuppressWarnings("deprecation")
).
As a consequence, you should set the @Deprecated
annotation on the superclass and on the subclasses (as Sajan commented). You'll also need to add it to the other methods using these methods, recursively.
Please also note Rinke's good remark in his answer :
The @Deprecated annotation is not annotated with @Inherited. The annotation will therefore not automatically apply to the inherited method.
The logic behind is that everything that is using some deprecated code (=is not the right way to do anymore and to be removed in near future), should also be marked as "not the right way to do anymore and to be removed in near future".
If the behavior(code) of the method you want to deprecate is used in useful (non-deprecated) method, you should extract the code in another function that will be called by our other valid code.
Instead of:
@Deprecated
public void someMethodWithBadSignature() {
//some Code
}
public void otherValidMethod() {
someMethodWithBadSignature(); /// <====== WARNING
}
use :
@Deprecated
public void someMethodWithBadSignature() {
someMethodsCode();
}
private void someMethodCode() {
//your original code
}
public void otherValidMethod() {
someMethodCode();
}
Upvotes: 1