Content deleted Content added
Citation bot (talk | contribs) Added title. | Use this bot. Report bugs. | Suggested by Jay8g | #UCB_toolbar |
|||
(38 intermediate revisions by 23 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 |
|
|
|url-status=dead
}}</ref>
== History ==
The [[Java (software platform)|Java platform]] has
|title = JSR 175: A Metadata Facility for the JavaTM Programming Language|date = 2006-11-02
|
}}</ref>
Annotations became available in the language itself beginning with version 1.5 of the [[Java Development Kit]] (JDK). The [[Annotation processing tool
In [[C++26]], [[C++]] added annotations for reflection that are similar to Java annotations.
== Built-in annotations ==
Line 25 ⟶ 28:
| title = Predefined Annotation Types
| publisher = [[Oracle Corporation]]
|
}}</ref><ref>{{cite web
| url = http://www.java2s.com/Tutorial/Java/0020__Language/TheBuiltInAnnotations.htm
| title = The Built-In Annotations : Standard Annotations
|
}}</ref>
{| class="wikitable"
! Annotation !! Package !! Description
|-
|-
| <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
| 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"
! Annotation !! Package !! Description
|-
| <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.
|}
== 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
<syntaxhighlight lang="java">
public class Animal {
public void speak() {}
public String getType() {
Line 80 ⟶ 136:
=== Custom annotations ===
Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the
<syntaxhighlight lang=Java>
}
// 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>
</syntaxhighlight>
Line 116 ⟶ 174:
<syntaxhighlight lang=Java>
</syntaxhighlight>
Line 155 ⟶ 212:
</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 [[
A complete example is given below:
<syntaxhighlight lang=Java>
package com.acme.proj.annotation;
import java.lang.annotation.Documented;
Line 171 ⟶ 228:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.TYPE, ElementType.METHOD, }) @Inherited
public @interface Unfinished {
public enum Priority { LOW, MEDIUM, HIGH }
Line 188 ⟶ 246:
<syntaxhighlight lang=Java>
package com.acme.proj.annotation;
public @interface UnderConstruction {
Line 199 ⟶ 257:
<syntaxhighlight lang=Java>
package com.acme.proj.validators;
import javax.faces.application.FacesMessage;
Line 207 ⟶ 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 {
String date = (String) value;
String errorLabel = "Please enter a valid date.";
Line 224 ⟶ 281:
if (!Util.validateAGivenDate(date)) {
@Unfinished(
changedBy = "Steve", value = "whether to add message to context or not, confirm",
priority = Priority.HIGH
Line 242 ⟶ 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 their own code that uses
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 258 ⟶ 316:
String developer() default "Unknown";
String lastModified();
String
int meaningOfLife();
}
Line 265 ⟶ 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 281 ⟶ 340:
public class UseCustomAnnotation {
public static void main(String
Class<SetCustomAnnotation> classObject = SetCustomAnnotation.class;
readAnnotation(classObject);
Line 288 ⟶ 347:
static void readAnnotation(AnnotatedElement element) {
try {
System.out.println("Annotation element values:
if (element.isAnnotationPresent(TypeHeader.class)) {
// getAnnotation returns Annotation type
Annotation singleAnnotation = element.getAnnotation(TypeHeader.class);
TypeHeader header = (TypeHeader) singleAnnotation;
System.out.
System.out.
// teamMembers returned as String
System.out.print("Team members: ");
for (String member : header.teamMembers()) {
System.out.
System.out.println();
System.out.println("Meaning of Life: %s%n"
}
} catch (Exception exception) {
Line 312 ⟶ 371:
}
</syntaxhighlight>
== See also ==
* [[
* [[Metadata (CLI)#Attributes|CLI Attribute]]s
* [[Java (programming language)|Java]]
* [[Java virtual machine]]
* [[Model-driven architecture]]
Line 332 ⟶ 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]
*
*
*
*
*
<!--Categories-->
[[Category:Java (programming language)|annotation]]
[[Category:Articles with example Java code]]
[[Category:Java specification requests|annotation]]
|