Metadata for the compiler, does not create code.
The used annotation can be accessed in run-time through Reflection.
Marker annotation:
@AnnotationName()@AnnotationName1-element annotation:
@AnnotationName(value = elementValueString)@AnnotationName(elementValueString)Because it has only 1 element, the parameter is called value or can be left out.
Multi-element annotation:
@AnnotationName(value1 = elementValueString1, value1 = elementValueString1, ...)For classes, interfaces, fields, methods.
Place directly above a line it refers to.
A type annotation is used inline with the type it refers to.
a. Constructor annotation: used in calling constructor.
ArrayList<String> sal = new @ReadOnly ArrayList<>(); //the constructor will create a read-only objectb. Type definition annotation:
@NonNull String s; //gives warning in case an action with s would throw a NullPointerException@NonNull List<String> li; //through the warning, li must have minimum 1 elementList<@NonNull String> li2; //through the warning, all elements of li2 must not be null but minimum empty Stringc. Type cast annotation:
String s = (@NonNull String) str; //if str would be null, gives warningd. Extend and implement clause annotation:
class W extends @Localized M {...}e. Throws clause annotation:
public String read() throws @Localized IOExceptionUsed as declaration annotations.
@Deprecated //compiler gives warning in compile-time@Override@SuppressWarnings(value) //"unchecked": raw type usage, in JavaDocs should have to be documented; "deprecated"; {"deprecated", "unchecked"}@SafeVarargs //in case of variable number of arguments and unsafe action is made by the method, suppresses the warning, only for not-extendable (and from Java9 for private) methods@FunctionalInterface //the interface can have only abstract methodsModifies the validity of the following annotation.
@Retention(retentionPolicy) //RetentionPolicy.SOURCE: the annotation is seeable only in the source code, ~.CLASS: seeable only by the compiler, ~.RUNTIME: available for the JVM@Documented //the annotation will be mentioned in Javadocs@Target(elementType) //the annotation is limited to the given type (ElementType.CONSTRUCTOR, ~.FIELD, ~.METHOD, ~.PACKAGE)@Inherited //the annotation can be inherited@Repeatable(...) //the annotation can be more than once in the given class (e.g. Uni.class)Can be achieved by creating an interface for this purpose.
[Access Modifier] @interface AnnotationName { DataType methodName() [default defaultValue];}EXAMPLE FOR CUSTOM ANNOTATION: