Annotation in java
Element Types | Where the annotation can be applied |
TYPE | class, interface |
FIELD | fields |
METHOD | methods |
CONSTRUCTOR | constructors |
ANNOTATION_TYPE | annotation type |
LOCAL_VARIABLE | local variables |
PARAMETER | parameter |
Annotation
Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate. Or simply we can say , adding additional information about a program is done with annotations.
There are generally 5 types of annotations, as follows:
- Marker Annotations
- Single value Annotations
- Full Annotations
- Type Annotations
- Repeating Annotations
What is the use of Annotation ?
- Information for the compiler — The compiler can use annotations to identify errors or turn off warnings.
- Deployment and compilation— Annotation data can be processed in real-time by software tools to produce code, XML files, and other output.
- Processing done at runtime — Some annotations can be looked at right away.
Key Features of Annotation
- Annotations begin with an “@.”
- Annotations do not affect how a compiled program behaves.
- Instance variables, constructors, methods, classes, and other program elements can all be annotated to add metadata (information).
- As they can alter how a program is handled by the compiler, annotations are not simply comments.
- An alternative to XML and Java marker interfaces, annotations are essentially used to provide extra information.
Built-In Java Annotations
Java comes with a number of built-in annotations. A few annotations are used with Java code, while others are used with other annotations.
Java source code that uses built-in annotations
- @Override
- @SuppressWarnings
- @Deprecated
Java built-in Annotations used in other annotations
- @Target
- @Retention
- @Inherited
- @Documented
Declaring of an Annotation
Many annotations in code take the place of comments.
Consider a scenario where a software group customarily begins each class with comments outlining crucial information:
Example code :
public class Generation3List extends Generation2List { // Author: John Doe // Date: 3/17/2002 // Current revision: 6 // Last modified: 4/12/2004 // By: Jane Doe // Reviewers: Alice, Bill, Cindy // class code goes here }
The syntax for doing this is:
@interface ClassPreamble { String author(); String date(); int currentRevision() default 1; String lastModified() default "N/A"; String lastModifiedBy() default "N/A"; // Note use of array String[] reviewers(); }
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment