An annotation that is near and dear to my heart; as someone who constantly evolves their classes it is vital that if I cannot remove some old methods and/or fields at a single moment, I correctly identify that they should no longer be used and a new method or field should be used instead. I have also been seeing it more and more the last couple of days on the open source projects that I am viewing (which is strange as this is not the first time I am thinking about a certain concept and then it appears everywhere).
The reason why I really appreciate the @Deprecated and @deprecated Java annotations are because as your classes evolve you sometimes have to signal to the developers working on the project that “hey this should no longer be used, it has been superseded by another method and you should use that one instead”. Both these annotations do just that.
@Deprecated vs @deprecated
If you take a quick look at the annotations then you may not see the difference. But having a capital letter ‘D’ instead of a lower case letter ‘d’ is important.
The @Deprecated annotation is to let the compiler know to generate a warning whenever your program is using the class, method or field that has the annotation.
The @deprecated annotation is specifically used for the Javadoc and notifies to the developer to not use the class, method or field and use the appropriate superseded one.
Generally I use both. @Deprecated to actually deprecate the class, method or field and then the @deprecated annotation in a comment to highlight which superseded class, method or field to use instead, and also very importantly note why the class, method or field was deprecated.
I have seen plenty of times only @Deprecated is used with no information as to what to use instead, which is slightly frustrating. It is always worth spending a small amount of time to correctly document why something has been deprecated and what to use instead, it makes everything much easier for you and everyone else.
Using @Deprecated
It is very simple to use the annotation.
To deprecate a class:
@Deprecated public class Person { ... }
To deprecate a method:
public class Person { ... @Deprecated public String getName() { ... } ... }
To deprecate a field:
public class Person { .... @Deprecated private String name; ... }
Using @deprecated
Just as important as deprecating a class, method or field I believe in documenting what to use instead and why the original class, method or field has become deprecated. This annotation is sometimes missed by many developers from the open source projects that I have looked at.
To document a deprecated class, method or field:
/** * @deprecated * Replaced by {@link #Entity} * No longer valid as a Person objects are replaced by Entity objects. */ @Deprecated public class Person { ... }
Official Documentation
For more information about the two annotations then take a look at the official Oracle documentation, here.