- Details
- Written by Nam Ha Minh
- Last Updated on 22 August 2019   |   Print Email
When developing APIs which are publicly used by others, sometimes we have to replace the old APIs with newer, better and more efficient ones. A typical example is changing a method name to a new one which is more accurate or reflects more appropriate programming practices. In such case, we should keep the old method for backward compatibility with the existing users, whilst encourage them to use the alternate version in the Javadoc. This is referred as API deprecation.Since Java 1.5, programmers can use the
@Deprecated annotation type to mark a program’s element (class, method, field and constructor) deprecated. The following are some examples.
Java @Deprecated Examples:
- Deprecating a type (class or interface):
Deprecated interface:
@Deprecated
interface Kool {
// interface methods
}
Deprecated class:@Deprecated
class Foo {
// class implementation
}
- Deprecating a method:
class Bar {
@Deprecated
public void doSomethingWeird() {
// old method
}
public void doSomethingCool() {
// new, alternate method
}
}
- Deprecating a member variable (field):
class Constant {
@Deprecated
public static final int MAX_SIZE = 1024;
// new, alternate field
public static final int MAX_UPLOAD_SIZE = 1024;
}
- Deprecating a constructor:
class Car {
@Deprecated
Car(String color, int length, int width) {
}
// new, alternate constructor
Car(Style style) {
}
}
Some Rules about @Deprecated annotation:
Notes:
When using deprecation, it’s a good practice to provide reason for the deprecation and/or recommend alternative solution in the Javadoc of the deprecated element. For example, the following is Javadoc of a deprecated method of String class:
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated.
This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.
Reference: How and When To Deprecate APIs Other Annotations in Core Java:
Recommended Java Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on
Facebook and watch
his Java videos you YouTube.