Built-in Annotations
Annotations Java already understands
You do not need to create your own annotation for common tasks. Java already provides a set of standard types that help verify developer intent, document obsolete APIs, and control compiler diagnostics.
@Override — checking an override
@Override should be used whenever a method overrides a superclass method
or implements an interface method. It turns the developer's intention into a condition the compiler can verify.
class User {
@Override
public String toString() {
return "User";
}
}
If the method name or parameters are accidentally changed later, the compiler will not silently allow a new method that is unrelated to the intended override.
@Deprecated — an API should no longer be used
@Deprecated marks an API whose use is discouraged.
The annotation has since and forRemoval elements:
the first helps state when the deprecation status appeared, while the second indicates whether removal is planned.
@Deprecated(since = "2.0", forRemoval = true)
void oldMethod() {
}
Such an annotation is usually accompanied by Javadoc explaining the reason and the recommended replacement.
@SuppressWarnings — suppressing a warning precisely
@SuppressWarnings tells the compiler not to report selected warnings
for a particular element. It is useful to place it as close as possible to the location where the warning is consciously accepted,
rather than disabling diagnostics for a large class without a reason.
@SuppressWarnings("unchecked")
void convert(Object value) {
var list = (java.util.List<String>) value;
}
Other common standard annotations
@FunctionalInterfacerecords the intention to have exactly one abstract method suitable for lambda expressions.@SafeVarargsis used in permitted locations when the developer guarantees safe use of generic varargs.