Java Annotations
Annotations are metadata bound to elements of the source code of a program and have no effect on the operation of the code they operate.
Their typical uses cases are:
- Information for the compiler – with annotations, the compiler can detect errors or suppress warnings
- Compile-time and deployment-time processing – software tools can process annotations and generate code, configuration files, etc.
- Runtime processing – annotations can be examined at runtime to customize the behavior of a program
There are several annotations in the java.lang and java.lang.annotation packages, the more common ones include but not limited to:
- @Override – marks that a method is meant to override an element declared in a superclass. If it fails to override the method correctly, the compiler will issue an error
- @Deprecated – indicates that element is deprecated and should not be used. The compiler will issue a warning if the program uses a method, class, or field marked with this annotation
- @SuppressWarnings – tells the compiler to suppress specific warnings. Most commonly used when interfacing with legacy code written before generics appeared
- @FunctionalInterface – introduced in Java 8, indicates that the type declaration is a functional interface and whose implementation can be provided using a Lambda Expression
How Can You Create an Annotation?
Annotations are a form of an interface where the keyword interface is preceded by @, and whose body contains annotation type element declarations that look very similar to methods:
After the annotation is defined, yon can start using it in through your code:
Note that, when providing multiple values for array elements, you must enclose them in brackets.
Optionally, default values can be provided as long as they are constant expressions to the compiler:
Now, you can use the annotation without those elements:
Or only some of them:
Comments
Post a Comment