e01.org

Java annotation

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code, like an attribute. 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.

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code, like an attribute. 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. There was previously an annotation, @ManagedBean , located in jakarta.annotation , which was historically used to declare a Managed Bean which are container managed objects that support a small set of basic services such as resource injection, lifecycle callbacks and interceptors. However, it has been removed. 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"; } } // @Twizzle is an annotation to method toggle(). @Twizzle public void toggle() { } // Declares the annotation Twizzle. public @interface Twizzle { } Annotations may include a set of key-value pairs, which are modeled as methods of the annotation type. 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. // 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: import java.lang.annotation.*; @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 @Deprecated , @Override and @SuppressWarnings ) for syntactic purposes. Annotations are widely used by frameworks as a way of conveniently applying behaviors 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). For instance, the library Project Lombok makes extensive usage of annotations to reduce boilerplate. The following, for example, is an annotated Jakarta Persistence data class: package org.wikipedia.examples; import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GenerationType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.Table; @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 Jakarta Persistence implementation at run-time, which then extracts the annotations to generate an object–relational mapping. A complete example is given below: package org.wikipedia.examples.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 { public enum Priority { LOW, MEDIUM, HIGH } 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 org.wikipedia.examples.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"; } Then, using Jakarta Faces: package org.wikipedia.examples.validators; import jakarta.faces.application.FacesMessage; import jakarta.faces.component.UIComponent; import jakarta.faces.context.FacesContext; import jakarta.faces.validator.Validator; import jakarta.faces.validator.ValidatorException; import org.wikipedia.examples.annotation.UnderConstruction; import org.wikipedia.examples.annotation.Unfinished; import org.wikipedia.examples.annotation.Unfinished.Priority; import org.wikipedia.examples.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); } } } package org.wikipedia.examples.annotation; 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 } package org.wikipedia.examples; // 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 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.printf("Developer: %s%n", header.developer()); System.out.printf("Last Modified: %s%n", header.lastModified()); // teamMembers returned as String[] System.out.print("Team members: "); for (String member : header.teamMembers()) { System.out.printf("%s, ", member); } System.out.println(); System.out.println("Meaning of Life: %s%n", header.meaningOfLife()); } } catch (Exception e) { e.printStackTrace(); } } } Libraries such as JUnit use annotation processing to generate unit tests.

source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"Java annotation". 1783306758. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1362786807

JSON record · API collection · citation policy