HOME

TheInfoList



OR:

In the Java computer programming language, an annotation is a form of syntactic
metadata Metadata is "data that provides information about other data", but not the content of the data, such as the text of a message or the image itself. There are many distinct types of metadata, including: * Descriptive metadata – the descriptive ...
that can be added to Java
source code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the ...
. Classes,
methods Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
, variables,
parameters A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
and
Java package A Java package organizes Java classes into namespaces, providing a unique namespace for each type it contains. Classes in the same package can access each other's package-private and protected members. In general, a package can contain the follo ...
s may be annotated. Like
Javadoc Javadoc (originally cased JavaDoc) is a documentation generator created by Sun Microsystems for the Java language (now owned by Oracle Corporation) for generating API documentation in HTML format from Java source code. The HTML format is used for ...
tags, Java annotations can be read from source files. Unlike
Javadoc Javadoc (originally cased JavaDoc) is a documentation generator created by Sun Microsystems for the Java language (now owned by Oracle Corporation) for generating API documentation in HTML format from Java source code. The HTML format is used for ...
tags, Java annotations can also be embedded in and read from
Java class file A Java class file is a file (with the filename extension) containing Java bytecode that can be executed on the Java Virtual Machine (JVM). A Java class file is usually produced by a Java compiler from Java programming language source files ...
s generated by the
Java compiler A Java compiler is a compiler for the programming language Java. The most common form of output from a Java compiler is Java class files containing platform-neutral Java bytecode, but there are also compilers that output optimized native machine ...
. This allows annotations to be retained by the
Java virtual machine A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describe ...
at run-time and read via
reflection Reflection or reflexion may refer to: Science and technology * Reflection (physics), a common wave phenomenon ** Specular reflection, reflection from a smooth surface *** Mirror image, a reflection in a mirror or in water ** Signal reflection, in ...
. It is possible to create meta-annotations out of the existing ones in Java.


History

The
Java platform Java is a set of computer software and specifications developed by James Gosling at Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cro ...
has various ''ad-hoc'' annotation mechanisms—for example, the ''transient'' modifier, or the ''@Deprecated'' javadoc tag. The
Java Specification Request The Java Community Process (JCP), established in 1998, is a formalized mechanism that allows interested parties to develop standard technical specifications for Java technology. Anyone can become a JCP Member by filling a form available at thJCP w ...
JSR-175 introduced the general-purpose annotation (also known as ''metadata'') facility to the
Java Community Process The Java Community Process (JCP), established in 1998, is a formalized mechanism that allows interested parties to develop standard technical specifications for Java technology. Anyone can become a JCP Member by filling a form available at thJCP w ...
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 The Java Development Kit (JDK) is a distribution of Java Technology by Oracle Corporation. It implements the Java Language Specification (JLS) and the Java Virtual Machine Specification (JVMS) and provides the Standard Edition (SE) of the Java ...
(JDK). The apt 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 javac (pronounced "java-see") is the primary Java compiler included in the Java Development Kit (JDK) from Oracle Corporation. Martin Odersky implemented the GJ compiler, and his implementation became the basis for javac. The compiler accept ...
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: * @Override - Checks that the method is an override. Causes a
compilation error Compilation error refers to a state when a compiler fails to compile a piece of computer program source code, either due to errors in the code, or, more unusually, due to errors in the compiler itself. A compilation error message often helps program ...
if the method is not found in one of the
parent class In object-oriented programming, inheritance is the mechanism of basing an Object (computer science), object or Class (computer programming), class upon another object (Prototype-based programming, prototype-based inheritance) or class (Class-based ...
es or implemented
interfaces Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Int ...
. * @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used. * @SuppressWarnings - Instructs the compiler to suppress the
compile time In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concep ...
warnings specified in the annotation parameters. Annotations applied to other annotations (also known as "Meta Annotations"): * @Retention - Specifies how the marked annotation is stored, whether in code only, compiled into the class, or available at runtime through reflection. * @Documented - Marks another annotation for inclusion in the documentation. * @Target - Marks another annotation to restrict what kind of Java elements the annotation may be applied to. * @Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited by subclasses). Since Java 7, three additional annotations have been added to the language. * @SafeVarargs - Suppress warnings for all callers of a method or constructor with a
generics Generic or generics may refer to: In business * Generic term, a common name used for a range or class of similar things not protected by trademark * Generic brand, a brand for a product that does not have an associated brand or trademark, other ...
varargs In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages. The term ''vari ...
parameter, since Java 7. * @FunctionalInterface - Specifies that the type declaration is intended to be a functional interface, since Java 8. * @Repeatable - Specifies that the annotation can be applied more than once to the same declaration, since Java 8.


Example


Built-in annotations

This example demonstrates the use of the @Override annotation. It instructs the compiler to check parent classes for matching methods. In this case, an error is generated because the gettype() method of class Cat doesn't in fact override getType() of class Animal like is desired, because of the mismatching case. If the @Override annotation were absent, a new method of name gettype() would be created in class Cat. public class Animal public class Cat extends Animal


Custom annotations

Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the keyword "interface". // @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 @Author(first = "Oompah", last = "Loompah") Book book = new Book(); public @interface Author 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() // 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 often used by
frameworks A framework is a generic term commonly referring to an essential supporting structure which other things are built on top of. Framework may refer to: Computing * Application framework, used to implement the structure of an application for an op ...
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 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 Object–relational mapping (ORM, O/RM, and O/R mapping tool) in computer science is a programming technique for converting data between type systems using object-oriented programming languages. This creates, in effect, a "virtual object dat ...
. 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() @Inherited public @interface Unfinished package com.annotation; public @interface UnderConstruction 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


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 RetentionPolicy of CLASS or RUNTIME. Later, the
JVM A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describes ...
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 his own code that uses reflections to process the annotation.
Java SE Java Platform, Standard Edition (Java SE) is a computing platform for development and deployment of portable code for desktop and server environments. Java SE was formerly known as Java 2 Platform, Standard Edition (J2SE). The platform uses Ja ...
5 supports a new interface that is defined in the java.lang.reflect package. This package contains the interface called AnnotatedElement that is implemented by the Java reflection classes including Class, Constructor, Field, Method, and Package. 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 AnnotatedElement interface provides access to annotations having RUNTIME retention. This access is provided by the getAnnotation, getAnnotations, and isAnnotationPresent 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 // This is the annotation being applied to a class @TypeHeader(developer = "Bob Bee", lastModified = "2013-02-12", teamMembers = , meaningOfLife = 42) public class SetCustomAnnotation // This is the example code that processes the annotation import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; public class UseCustomAnnotation


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.


See also

* Jakarta Annotations * CLI Attributes *
Java programming Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let programmers ''write once, run any ...
*
Java virtual machine A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describe ...
*
Model-driven architecture Model Driven Architecture (MDA) is a software design approach for the development of software systems. It provides a set of guidelines for the structuring of specifications, which are expressed as models. Model Driven Architecture is a kind of doma ...
* Python decorators, inspired by Java annotations, which have a similar syntax.


References

{{Reflist, 2


External links


Introduction to Java 6 Annotations at Sun Developer Network Site

An Introduction to Java Annotations by M. M. Islam Chisty

Introduction to Java 5.0 Annotations by Joy Christy

Of Java Annotations by John Hunt

Custom Annotations in Java




Java (programming language) Articles with example Java code Java specification requests