Java annotation: Difference between revisions

Content deleted Content added
Citation bot (talk | contribs)
Added title. | Use this bot. Report bugs. | Suggested by Jay8g | #UCB_toolbar
 
(16 intermediate revisions by 5 users not shown)
Line 1:
{{Short description|Syntactic metadata for Java source code}}
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 ==
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
{{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>
 
</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.
 
In [[C++26]], [[C++]] added annotations for reflection that are similar to Java annotations.
 
== Built-in annotations ==
Line 26 ⟶ 28:
| 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 applied to Java code:'''
! Annotation !! Package !! Description
* <code>@Override</code> - Checks that the method is an [[Method overriding|override]]. Causes a [[compilation error]] if the method is not found in one of the [[parent class]]es or implemented [[Interface (Java)|interfaces]].
|-
* <code>@Deprecated</code> - Marks the method as obsolete. Causes a compile warning if the method is used.
*| <code>@SuppressWarningsDeprecated</code> -|| Instructs<code>java.lang</code> the|| compilerMarks tothe suppressmethod theas [[compileobsolete. time]]Causes warningsa specifiedcompile inwarning if the annotationmethod is parametersused.
|-
| <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
'''Annotations applied to other annotations (also known as "Meta Annotations"):'''
| title = Jakarta Annotations API 1.3.5 API
| 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"
* <code>@Retention</code> - Specifies how the marked annotation is stored, whether in code only, compiled into the class, or available at runtime through reflection.
! Annotation !! Package !! Description
* <code>@Documented</code> - Marks another annotation for inclusion in the documentation.
|-
* <code>@Target</code> - Marks another annotation to restrict what kind of Java elements the annotation may be applied to.
*| <code>@InheritedGenerated</code> - Marks another|| <code>jakarta.annotation</code> to|| beMarks inheritedsource tocode subclassesthat ofhas annotatedbeen classgenerated (i.e. not written by defaulta annotationsuser, areor notautomatically inheritedgenerated by subclassesa computer).
|-
 
| <code>@Resource</code> || <code>jakarta.annotation</code> || Marks a class, method, or field as a reference to a resource.
Since Java 7, three additional annotations have been added to the language.
|-
 
| <code>@Resources</code> || <code>jakarta.annotation</code> || Declares reference to resources, as a container for multiple resource declarations.
* <code>@SafeVarargs</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>@FunctionalInterface </code> - Specifies that the [[Declaration (computer programming)|type declaration]] is intended to be a [[Anonymous function|functional interface]], since Java 8.
| <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>@Repeatable</code> - Specifies that the annotation can be applied more than once to the same declaration, since Java 8.
|-
| <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.
|}
 
== Example ==
 
=== Built-in annotations ===
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">
public class Animal {
public void speak() {}
}
 
public String getType() {
Line 84 ⟶ 139:
 
<syntaxhighlight lang=Java>
// @Twizzle is an annotation to method toggle().
@Twizzle
public void toggle() {
}
 
}
// Declares the annotation Twizzle.
 
public @interface Twizzle {
// Declares the annotation Twizzle.
}
public @interface Twizzle {
 
}
</syntaxhighlight>
 
Line 97 ⟶ 154:
 
<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>
 
Line 117 ⟶ 174:
 
<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>
 
Line 161 ⟶ 217:
 
<syntaxhighlight lang=Java>
package com.acme.proj.annotation;
 
import java.lang.annotation.Documented;
Line 172 ⟶ 228:
@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 }
Line 189 ⟶ 246:
 
<syntaxhighlight lang=Java>
package com.acme.proj.annotation;
 
public @interface UnderConstruction {
Line 200 ⟶ 257:
 
<syntaxhighlight lang=Java>
package com.acme.proj.validators;
 
import javax.faces.application.FacesMessage;
Line 208 ⟶ 265:
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 {
throws ValidatorException {
String date = (String) value;
String errorLabel = "Please enter a valid date.";
Line 225 ⟶ 281:
 
if (!Util.validateAGivenDate(date)) {
@Unfinished(
changedBy = "Steve",
value = "whether to add message to context or not, confirm",
priority = Priority.HIGH
Line 243 ⟶ 300:
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 histheir own code that uses reflectionsreflection 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:
Line 259 ⟶ 316:
String developer() default "Unknown";
String lastModified();
String [] teamMembers();
int meaningOfLife();
}
Line 266 ⟶ 323:
<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
Line 282 ⟶ 340:
 
public class UseCustomAnnotation {
public static void main(String [] args) {
Class<SetCustomAnnotation> classObject = SetCustomAnnotation.class;
readAnnotation(classObject);
Line 289 ⟶ 347:
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);
element.getAnnotation(TypeHeader.class);
TypeHeader header = (TypeHeader) singleAnnotation;
 
System.out.printlnprintf("Developer: %s%n" +, header.developer());
System.out.printlnprintf("Last Modified: %s%n" +, header.lastModified());
 
// teamMembers returned as String []
System.out.print("Team members: ");
for (String member : header.teamMembers()) {
System.out.printprintf(member + "%s, ", member);
System.out.print("\n");}
System.out.println();
 
System.out.println("Meaning of Life: %s%n"+, header.meaningOfLife());
}
} catch (Exception exception) {
Line 328 ⟶ 386:
* [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/ Introduction to Java 5.0 Annotations|archive-date=May by31, Joy2015 Christy]|website=JavaBeat}}
* [http{{Cite web |last=Hunt |first=John |title=Of Java Annotations |url=https://www.regdevelopertheregister.co.ukcom/2006/02/24/java_annotations/ Of|date=24 JavaFeb Annotations2006 by|website=The JohnRegister Hunt]|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/ Custom|archive-date=Feb Annotations23, in2014 Java]|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 Java Annotations Explained]|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 Understanding|website=Java Annotationsby in Java]examples}}
 
<!--Categories-->
[[Category:Java (programming language)|annotation]]
[[Category:Articles with example Java code]]
[[Category:Java specification requests|annotation]]