Java annotation: Difference between revisions

Content deleted Content added
Stagalj (talk | contribs)
History: Clarified paragraph
Citation bot (talk | contribs)
Added title. | Use this bot. Report bugs. | Suggested by Jay8g | #UCB_toolbar
 
(262 intermediate revisions by more than 100 users not shown)
Line 1:
{{Short description|Syntactic metadata for Java source code}}
In [[computer programming]], annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.
In the [[Java (programming language)|Java computer programming language]], an '''annotation''' is a form of syntactic [[metadata]] that can be added to Java [[source code]], like an [[Attribute (computing)|attribute]].<ref>{{cite web|url = http://download.oracle.com/javase/1,5.0/docs/guide/language/annotations.html|title = Annotations|access-date = 2011-09-30|publisher = [[Sun Microsystems]]|archive-url = https://web.archive.org/web/20110925021948/http://download.oracle.com/javase/1,5.0/docs/guide/language/annotations.html|archive-date = 2011-09-25|url-status = dead}}.</ref> [[Class (computer programming)|Classes]], [[Method (computer programming)|methods]], [[Variable (computer science)|variables]], [[Parameter (computer programming)|parameters]] and [[Java package]]s 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 file]]s generated by the [[Java compiler]]. This allows annotations to be retained by the [[Java virtual machine]] at [[Run time (program lifecycle phase)|run-time]] and read via [[reflection (computer science)|reflection]].<ref>{{Cite book|title = Java(TM) Language Specification|edition = 3rd|publisher = [[Prentice Hall]]|year = 2005|isbn = 0-321-24678-0|url = http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html|author = Sun Microsystems|author-link = Sun Microsystems}}.</ref> It is possible to create meta-annotations out of the existing ones in Java.<ref>{{cite web
|url=http://www.25hoursaday.com/
|title=A COMPARISON OF MICROSOFT'S C# PROGRAMMING LANGUAGE TO SUN MICROSYSTEMS' JAVA PROGRAMMING LANGUAGE: Metadata Annotations
|author=Dare Obasanjo
|year=2007
|publisher=Dare Obasanjo
|archive-url=https://web.archive.org/web/20120919093308/http://25hoursaday.com/
|archive-date=2012-09-19
|access-date=2012-09-20
|url-status=dead
}}</ref>
 
== History ==
Annotations have a number of uses; the most visible among them are:
The [[Java (software platform)|Java platform]] has various ''ad-hoc'' annotation mechanisms—for example, the ''<code>transient</code>'' modifier, or the ''<code>@Deprecated</code>'' 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.<ref>{{cite web
|url = http://www.jcp.org/en/jsr/detail?id=175#2
|title = JSR 175: A Metadata Facility for the JavaTM Programming Language|date = 2006-11-02
|access-date = 2008-03-05|first = Danny|last = Coward|publisher = [[Java Community Process]]
}}</ref>
 
Annotations became available in the language itself beginning with version 1.5 of the [[Java Development Kit]] (JDK). The [[Annotation processing tool|<code>apt</code> 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.
* Information for the compiler — used by the compiler to detect errors or suppress warnings.
 
In [[C++26]], [[C++]] added annotations for reflection that are similar to Java annotations.
* Compiler-time and deployment-time processing — annotation processor can process annotation information to produce new source code and other files.
 
== Built-in annotations ==
* Runtime processing — some annotations are available to be examined at runtime.
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.<ref>{{cite web
| url = https://docs.oracle.com/javase/tutorial/java/annotations/predefined.html
| title = Predefined Annotation Types
| publisher = [[Oracle Corporation]]
| access-date = 2016-12-17
}}</ref><ref>{{cite web
| url = http://www.java2s.com/Tutorial/Java/0020__Language/TheBuiltInAnnotations.htm
| title = The Built-In Annotations : Standard Annotations
| access-date = 2016-12-17
}}</ref>
 
{| class="wikitable"
Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements. Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.
! Annotation !! Package !! Description
|-
| <code>@Deprecated</code> || <code>java.lang</code> || Marks the method as obsolete. Causes a compile warning if the method is used.
|-
| <code>@FunctionalInterface</code> || <code>java.lang</code> || Marks an interface as intended to be a functional interface.
|-
| <code>@Override</code> || <code>java.lang</code> || Marks that the method [[Method overriding|overrides]] an ancestor class-defined method. Causes a [[compilation error]] if the method is not found in one of the [[parent class]]es or implemented [[Interface (Java)|interfaces]].
|-
| <code>@SafeVarargs</code> || <code>java.lang</code> || Suppress warnings for all callers of a method or constructor with a [[Generics in Java|generics]] [[Variadic function|varargs]] parameter, since Java 7.
|-
| <code>@SuppressWarnings</code> || <code>java.lang</code> || Instructs the compiler to suppress the [[compile time]] warnings specified in the annotation parameters.
|-
| <code>@Documented</code> || <code>java.lang.annotation</code> || Marks another annotation for inclusion in the documentation.
|-
| <code>@Inherited</code> || <code>java.lang.annotation</code> || Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited by subclasses).
|-
| <code>@Native</code> || <code>java.lang.annotation</code> || Marks a field defining a constant value as potentially being referenced from native code.
|-
| <code>@Repeatable</code> || <code>java.lang.annotation</code> || Marks another annotation as repeatable.
|-
| <code>@Retention</code> || <code>java.lang.annotation</code> || Specifies how the marked annotation is stored, whether in code only, compiled into the class, or available at runtime through reflection.
|-
| <code>@Target</code> || <code>java.lang.annotation</code> || Marks another annotation to restrict what kind of Java elements the annotation may be applied to.
|}
 
In [[Jakarta EE]] (formerly Java Platform, Enterprise Edition), the following annotations also exist in <code>jakarta.annotation</code> (formerly <code>javax.annotation</code>):<ref>{{cite web
==History==
| title = Jakarta Annotations API 1.3.5 API
The Java platform has always had various ad hoc annotation mechanisms - for example, the transient modifier, or the @deprecated javadoc tag. The general purpose annotation(also known as metadata) facility was introduced to the [[Java Community Process]] as JSR-175 in 2002 and approved in September 2004. This type of annotation became available with the [[JDK]] version 1.5. A provisional interface for compile-time annotation processing was provided by the apt tool in JDK version 1.5, and was formalized through JSR-269 and integrated into the [[javac]] compiler in version 1.6.
| url = https://jakartaee.github.io/common-annotations-api/apidocs/
| publisher = [[Jakarta EE]]
| access-date = 2025-08-13
}}</ref><ref>{{cite web
| title = Jakarta Annotations
| url = https://jakarta.ee/specifications/annotations/3.0/annotations-spec-3.0.html
| publisher = [[Jakarta EE]]
| access-date = 2025-08-13
}}</ref>
 
{| class="wikitable"
==Processing==
! Annotation !! Package !! Description
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, but processors cannot modify the annotated code itself. The Java compiler conditionally stores annotation metadata in the class files if the annotation has a RetentionPolicy of CLASS or RUNTIME. Later, the [[JVM]] or other programs can look for the metadata to determine how to interact with the program elements or change their behavior.
|-
| <code>@Generated</code> || <code>jakarta.annotation</code> || Marks source code that has been generated (i.e. not written by a user, or automatically generated by a computer).
|-
| <code>@Resource</code> || <code>jakarta.annotation</code> || Marks a class, method, or field as a reference to a resource.
|-
| <code>@Resources</code> || <code>jakarta.annotation</code> || Declares reference to resources, as a container for multiple resource declarations.
|-
| <code>@PostConstruct</code> || <code>jakarta.annotation</code> || Marks a method to indicate that it must be executed after dependency injection to perform initialization, i.e. the method must be invoked before the class is used.
|-
| <code>@PreDestroy</code> || <code>jakarta.annotation</code> || Marks a method as a callback notification to indicate the instance is in the process of being removed by the container, i.e. the method is used to release resources held by the instance.
|-
| <code>@Priority</code> || <code>jakarta.annotation</code> || Marks any program element to indicate in what order they should be used.
|-
| <code>@Nonnull</code> || <code>jakarta.annotation</code> || Marks any element that cannot be <code>null</code>.
|-
| <code>@Nullable</code> || <code>jakarta.annotation</code> || Marks any element that has the explicit possibility of being <code>null</code>.
|-
| <code>@RunAs</code> || <code>jakarta.annotation</code> || Defines the security role of the application during execution in a Jakarta EE container.
|-
| <code>@RolesAllowed</code> || <code>jakarta.annotation.security</code> || Marks a method to specify security roles permitted to access the method.
|-
| <code>@PermitAll</code> || <code>jakarta.annotation.security</code> || Marks a method to specify that all security roles may access the method.
|-
| <code>@DenyAll</code> || <code>jakarta.annotation.security</code> || Marks a method to specify that no security roles may access the method.
|-
| <code>@DeclareRoles</code> || <code>jakarta.annotation.security</code> || Specifies security roles used by the application.
|-
| <code>@DataSourceDefinition</code> || <code>jakarta.annotation.sql</code> || Defines a container <code>DataSource</code> that is registered with [[Java Naming and Directory Interface]] (JNDI).
|-
| <code>@DataSourceDefinitions</code> || <code>jakarta.annotation.sql</code> || Declares a container <code>DataSource</code>, acting as a container for multiple data source declarations.
|}
 
==Syntax Example ==
Declaring an annotation is a variation on tags that have been added to comment sections in the past.
 
=== Built-in annotations ===
Annotations take the form of an interface declaration with an @ preceding it and optionally marked with meta-annotations, as shown below:
This example demonstrates the use of the <code>@Override</code> annotation. It instructs the compiler to check parent classes for matching methods. In this case, an error is generated because the <code>gettype()</code> method of class Cat doesn't in fact override <code>getType()</code> of class Animal like is desired, because of the [[Case sensitivity|mismatching case]]. If the <code>@Override</code> annotation were absent, a new method of name <code>gettype()</code> would be created in class Cat.
 
<syntaxhighlight lang="java">
@Retention(RetentionPolicy.RUNTIME)
public class Animal {
@Target({ElementType.METHOD})
public void speak() {}
 
public String getType() {
In the above example both Retention and Target are examples of annotations.
return "Generic animal";
}
}
 
public class Cat extends Animal {
==Impact and Perception==
@Override
===Pros===
public void speak() { // This is a good override.
; Declarative programming : Annotations allow the programmer to declare in their source code how the software should behave. It is an example of how declarative programming constructs can be added to an object oriented language.
System.out.println("Meow.");
}
 
@Override
===Cons===
public String gettype() { // Compile-time error due to typo: should be getType() not gettype().
; Performance : Adding metadata to a run time causes additional memory overhead.
return "Cat";
; Standards lack : There are few standards that dictate what metadata tags should be used.
}
}
</syntaxhighlight>
 
=== Custom annotations ===
==See also==
* [[Java programming]]
* [[Model-driven architecture]]
* [[Java virtual machine]]
* [[Common Language Infrastructure|.Net CLI]] (Uses 'Attribute' constructs to achieve the same effect).
 
Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the [[Reserved word|keyword]] "interface".
==References==
* [http://www.jcp.org/en/jsr/detail?id=175 JSR 175: A Metadata Facility for the JavaTM Programming Language]
 
<syntaxhighlight lang=Java>
==External links==
// @Twizzle is an annotation to method toggle().
*[http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html Annotations]
@Twizzle
public void toggle() {
 
}
* [http://www.developer.com/java/other/article.php/3556176 An Introduction to Java Annotations]
 
// Declares the annotation Twizzle.
public @interface Twizzle {
 
}
</syntaxhighlight>
 
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 [[Primitive data type|primitives]], [[String (computer science)|String]], Class, [[Enumerated type|enums]], annotations, and [[Array data type|arrays]] of the preceding types. Methods can have [[Default (computer science)|default values]].
 
<syntaxhighlight lang=Java>
// 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();
}
</syntaxhighlight>
 
Annotations themselves may be annotated to indicate where and when they can be used:
 
<syntaxhighlight lang=Java>
@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 {}
</syntaxhighlight>
 
The compiler reserves a set of special annotations (including <code>@Deprecated</code>, <code>@Override</code> and <code>@SuppressWarnings</code>) for syntactic purposes.
 
Annotations are often used by [[software framework|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 [[Java Persistence API|JPA]] data class:
 
<syntaxhighlight lang=Java>
@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;
}
}
</syntaxhighlight>
 
The annotations are not method calls and will not, by themselves, do anything. Rather, the class object is passed to the [[Java Persistence API|JPA]] implementation at [[Run time (program lifecycle phase)|run-time]], which then extracts the annotations to generate an [[object–relational mapping]].
 
A complete example is given below:
 
<syntaxhighlight lang=Java>
package com.acme.proj.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";
}
</syntaxhighlight>
 
<syntaxhighlight lang=Java>
package com.acme.proj.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";
}
</syntaxhighlight>
 
<syntaxhighlight lang=Java>
package com.acme.proj.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.acme.proj.annotation.UnderConstruction;
import com.acme.proj.annotation.Unfinished;
import com.acme.proj.annotation.Unfinished.Priority;
import com.acme.proj.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);
}
}
}
</syntaxhighlight>
 
== 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 <code>RetentionPolicy</code> of <code>CLASS</code> or <code>RUNTIME</code>. Later, the [[Java virtual machine|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 reflection to process the annotation. [[Java Platform, Standard Edition|Java SE]] 5 supports a new interface that is defined in the <code>java.lang.reflect</code> package. This package contains the interface called <code>AnnotatedElement</code> that is implemented by the Java reflection classes including <code>Class</code>, <code>Constructor</code>, <code>Field</code>, <code>Method</code>, and <code>Package</code>. 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 <code>AnnotatedElement</code> interface provides access to annotations having <code>RUNTIME</code> retention. This access is provided by the <code>getAnnotation</code>, <code>getAnnotations</code>, and <code>isAnnotationPresent</code> 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:
 
<syntaxhighlight lang=Java>
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();
}
</syntaxhighlight>
 
<syntaxhighlight lang=Java>
// 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
}
</syntaxhighlight>
 
<syntaxhighlight lang=Java>
// 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.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 exception) {
exception.printStackTrace();
}
}
}
</syntaxhighlight>
 
== See also ==
* [[Jakarta Annotations]]
* [[Metadata (CLI)#Attributes|CLI Attribute]]s
* [[Java (programming language)|Java]]
* [[Java virtual machine]]
* [[Model-driven architecture]]
* [[Python syntax and semantics#Decorators|Python decorators]], inspired by Java annotations, which have a similar syntax.
 
== References ==
{{compu-sci-stub}}
{{Reflist|2}}
 
== External links ==
[[Category:Java programming language]]
* [http://java.sun.com/javase/6/docs/technotes/guides/language/annotations.html Introduction to Java 6 Annotations at Sun Developer Network Site]
* [http://www.developer.com/java/other/article.php/3556176 An Introduction to Java Annotations by M. M. Islam Chisty]
* {{Cite web |last=Srinivasan |first=Krishna |date=August 11, 2007 |title=Annotations in Java 5.0 |url=http://www.javabeat.net/annotations-in-java-5-0/ |url-status=dead |archive-url=https://web.archive.org/web/20150531080324/http://www.javabeat.net/annotations-in-java-5-0/ |archive-date=May 31, 2015 |website=JavaBeat}}
* {{Cite web |last=Hunt |first=John |title=Of Java Annotations |url=https://www.theregister.com/2006/02/24/java_annotations/ |date=24 Feb 2006 |website=The Register |language=en}}
* {{Cite web |date=February 15, 2014 |title=How to create and implement custom annotations in Java? |url=http://www.somanyword.com/2014/02/how-to-create-and-implement-custom-annotations-in-java/ |url-status=dead |archive-url=https://web.archive.org/web/20140223113106/http://www.somanyword.com/2014/02/how-to-create-and-implement-custom-annotations-in-java/ |archive-date=Feb 23, 2014 |website=So Many Word}}
* {{Cite web |date=October 9, 2014 |title=Java Annotations Tutorial with examples |url=http://www.tutorialsdesk.com/2014/10/java-annotations-tutorial-with-examples.html |website=TutorialsDesk}}
* {{Cite web |last=Thakor |first=Vicky |date=13 October 2015 |title=Understanding Annotations in Java |url=http://www.javaquery.com/2015/10/understanding-annotations-in-java.html |website=Java by examples}}
 
<!--Categories-->
[[ca:Anotació (Java)]]
[[Category:Java (programming language)|annotation]]
[[de:Annotation (Java)]]
[[esCategory:AnotaciónArticles with example Java code]]
[[Category:Java specification requests|annotation]]
[[fr:Annotation (Java)]]
[[it:Annotazione (Java)]]
[[ja:アノテーション]]