Java annotation

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and Java packages may be annotated. Like Javadoc tags, Java annotations can be read from source files. Unlike Javadoc tags, Java annotations can also be embedded in and read from Java class files generated by the Java compiler. This allows annotations to be retained by the Java virtual machine at run-time and read via reflection. It is possible to create meta-annotations out of the existing ones in Java.
History.
The Java platform has various "ad-hoc" annotation mechanisms—for example, the "codice_1" modifier, or the "codice_2" javadoc tag. The Java Specification Request JSR-175 introduced the general-purpose annotation (also known as "metadata") facility to the Java Community Process in 2002; it gained approval in September 2004.
Annotations became available in the language itself beginning with version 1.5 of the Java Development Kit (JDK). The codice_3 tool provided a provisional interface for compile-time annotation processing in JDK version 1.5; JSR-269 formalized this, and it became integrated into the javac compiler in version 1.6.
Built-in annotations.
Java defines a set of annotations that are built into the language. Of the seven standard annotations, three are part of java.lang, and the remaining four are imported from java.lang.annotation.
Annotations applied to Java code:
Annotations applied to other annotations (also known as "Meta Annotations"):
Since Java 7, three additional annotations have been added to the language.
Example.
Built-in annotations.
This example demonstrates the use of the codice_4 annotation. It instructs the compiler to check parent classes for matching methods. In this case, an error is generated because the codice_15 method of class Cat doesn't in fact override codice_16 of class Animal like is desired, because of the mismatching case. If the codice_4 annotation were absent, a new method of name codice_15 would be created in class Cat.
public class Animal {
 public void speak() {
 public String getType() {
 return "Generic animal";
public class Cat extends Animal {
 @Override
 public void speak() { // This is a good override.
 System.out.println("Meow.");
 @Override
 public String gettype() { // Compile-time error due to typo: should be getType() not gettype().
 return "Cat";
Custom annotations.
Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the interface keyword. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. Methods can have default values.
 // @Twizzle is an annotation to method toggle().
 @Twizzle
 public void toggle() {
 // Declares the annotation Twizzle.
 public @interface Twizzle {
Annotations may include an optional list of key-value pairs:
 // Same as: @Edible(value = true)
 @Edible(true)
 Item item = new Carrot();
 public @interface Edible {
 boolean value() default false;
 @Author(first = "Oompah", last = "Loompah")
 Book book = new Book();
 public @interface Author {
 String first();
 String last();
Annotations themselves may be annotated to indicate where and when they can be used:
 @Retention(RetentionPolicy.RUNTIME) // Make this annotation accessible at runtime via reflection.
 @Target({ElementType.METHOD}) // This annotation can only be applied to class methods.
 public @interface Tweezable {
The compiler reserves a set of special annotations (including codice_5, codice_4 and codice_6) for syntactic purposes.
Annotations are often used by frameworks as a way of conveniently applying behaviours to user-defined classes and methods that must otherwise be declared in an external source (such as an XML configuration file) or programmatically (with API calls). The following, for example, is an annotated JPA data class:
@Entity // Declares this an entity bean
@Table(name = "people") // Maps the bean to SQL table "people"
public class Person implements Serializable {
 @Id // Map this to the primary key column.
 @GeneratedValue(strategy = GenerationType.AUTO) // Database will generate new primary keys, not us.
 private Integer id;
 @Column(length = 32) // Truncate column values to 32 characters.
 private String name;
 public Integer getId() {
 return id;
 public void setId(Integer id) {
 this.id = id;
 public String getName() {
 return name;
 public void setName(String name) {
 this.name = name;
The annotations are not method calls and will not, by themselves, do anything. Rather, the class object is passed to the JPA implementation at run-time, which then extracts the annotations to generate an object-relational mapping.
A complete example is given below:
package com.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,
 ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE,
 ElementType.PACKAGE,ElementType.FIELD,ElementType.LOCAL_VARIABLE})
@Inherited
public @interface Unfinished {
 String value();
 String[] changedBy() default "";
 String[] lastChangedBy() default "";
 Priority priority() default Priority.MEDIUM;
 String createdBy() default "James Gosling";
 String lastChanged() default "2011-07-08";
package com.annotation;
public @interface UnderConstruction {
 String owner() default "Patrick Naughton";
 String value() default "Object is Under Construction.";
 String createdBy() default "Mike Sheridan";
 String lastChanged() default "2011-07-08";
package com.validators;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import com.annotation.UnderConstruction;
import com.annotation.Unfinished;
import com.annotation.Unfinished.Priority;
import com.util.Util;
@UnderConstruction(owner="Jon Doe")
public class DateValidator implements Validator {
 public void validate(FacesContext context, UIComponent component, Object value)
 throws ValidatorException {
 String date = (String) value;
 String errorLabel = "Please enter a valid date.";
 if (!component.getAttributes().isEmpty()) {
 errorLabel = (String) component.getAttributes().get("errordisplayval");
 if (!Util.validateAGivenDate(date)) {
 @Unfinished(changedBy = "Steve",
 value = "whether to add message to context or not, confirm",
 priority = Priority.HIGH
 FacesMessage message = new FacesMessage();
 message.setSeverity(FacesMessage.SEVERITY_ERROR);
 message.setSummary(errorLabel);
 message.setDetail(errorLabel);
 throw new ValidatorException(message);
Processing.
When Java source code is compiled, annotations can be processed by compiler plug-ins called annotation processors. Processors can produce informational messages or create additional Java source files or resources, which in turn may be compiled and processed. However, annotation processors cannot modify the annotated code itself. (Code modifications may be implemented using methods beyond the Java Language Specification.) The Java compiler conditionally stores annotation metadata in the class files, if the annotation has a codice_22 of codice_23 or codice_24. Later, the JVM or other programs can look for the metadata to determine how to interact with the program elements or change their behavior.
In addition to processing an annotation using an annotation processor, a Java programmer can write their own code that uses reflections to process the annotation. Java SE 5 supports a new interface that is defined in the codice_25 package. This package contains the interface called codice_26 that is implemented by the Java reflection classes including codice_27, codice_28, codice_29, codice_30, and codice_31. The implementations of this interface are used to represent an annotated element of the program currently running in the Java Virtual Machine. This interface allows annotations to be read reflectively.
The codice_26 interface provides access to annotations having codice_24 retention. This access is provided by the codice_34, codice_35, and codice_36 methods. Because annotation types are compiled and stored in byte code files just like classes, the annotations returned by these methods can be queried just like any regular Java object. A complete example of processing an annotation is provided below:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
// This is the annotation to be processed
// Default for Target is all Java Elements
// Change retention policy to RUNTIME (default is CLASS)
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeHeader {
 // Default value specified for developer attribute
 String developer() default "Unknown";
 String lastModified();
 String [] teamMembers();
 int meaningOfLife();
// This is the annotation being applied to a class
@TypeHeader(developer = "Bob Bee",
 lastModified = "2013-02-12",
 teamMembers = { "Ann", "Dan", "Fran" },
 meaningOfLife = 42)
public class SetCustomAnnotation {
 // Class contents go here
// This is the example code that processes the annotation
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
public class UseCustomAnnotation {
 public static void main(String [] args) {
 Class<SetCustomAnnotation> classObject = SetCustomAnnotation.class;
 readAnnotation(classObject);
 static void readAnnotation(AnnotatedElement element) {
 try {
 System.out.println("Annotation element values: \n");
 if (element.isAnnotationPresent(TypeHeader.class)) {
 // getAnnotation returns Annotation type
 Annotation singleAnnotation = 
 element.getAnnotation(TypeHeader.class);
 TypeHeader header = (TypeHeader) singleAnnotation;
 System.out.println("Developer: " + header.developer());
 System.out.println("Last Modified: " + header.lastModified());
 // teamMembers returned as String []
 System.out.print("Team members: ");
 for (String member : header.teamMembers())
 System.out.print(member + ", ");
 System.out.print("\n");
 System.out.println("Meaning of Life: "+ header.meaningOfLife());
 } catch (Exception exception) {
 exception.printStackTrace();
Usage in the wild.
Researchers have studied the usage of Java annotations over 1,094 notable open-source Java projects hosted on GitHub. They found that annotations are actively maintained, with many annotations being added, but also changed or removed because of bugs in the annotation type or values. Overall, this study finds that there exists a small but significant relationship between annotation usage and code error-proneness: Java code with annotations
tends to be less error-prone.