The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
In its simplest form, an annotation looks like the following:
@Entity
The at sign character (@) indicates to the compiler that what follows is an annotation. In the following example, the annotation's name isOverride:
@Overridevoid mySuperMethod() { ... }The annotation can includeelements, which can be named or unnamed, and there are values for those elements:
@Author( name = "Benjamin Franklin", date = "3/27/2003")class MyClass { ... }or
@SuppressWarnings(value = "unchecked")void myMethod() { ... }If there is just one element namedvalue, then the name can be omitted, as in:
@SuppressWarnings("unchecked")void myMethod() { ... }If the annotation has no elements, then the parentheses can be omitted, as shown in the previous@Override example.
It is also possible to use multiple annotations on the same declaration:
@Author(name = "Jane Doe")@EBookclass MyClass { ... }If the annotations have the same type, then this is called a repeating annotation:
@Author(name = "Jane Doe")@Author(name = "John Smith")class MyClass { ... }Repeating annotations are supported as of the Java SE 8 release. For more information, seeRepeating Annotations.
The annotation type can be one of the types that are defined in thejava.lang orjava.lang.annotation packages of the Java SE API. In the previous examples,Override andSuppressWarnings arepredefined Java annotations. It is also possible to define your own annotation type. TheAuthor andEbook annotations in the previous example are custom annotation types.
Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.
As of the Java SE 8 release, annotations can also be applied to theuse of types. Here are some examples:
new @Interned MyObject();
myString = (@NonNull String) str;
implements clause: class UnmodifiableList<T> implements @Readonly List<@Readonly T> { ... } void monitorTemperature() throws @Critical TemperatureException { ... }This form of annotation is called atype annotation. For more information, seeType Annotations and Pluggable Type Systems.
About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights
Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.