Sage-Code Laboratory

Java Annotations

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Annotation Syntax

/* different annotations */
@annotation(value, value, ...) 
@annotation(name=value, name=value ...)

Using annotations

1. Annotations have multiple use cases. It can be used for declaration statements, above the declaration in a single line or multiple lines. Also more then one annotations can apply to one declaration.

2. As of the Java SE 8 release, annotations can also be applied to the use of types. Here are some examples:

/* Special annotations */
//Class instance creation expression
      new @Interned MyObject();
//Type cast with annotation
      myString = (@NonNull String) str;
//Implementation clause
      class UnmodifiableList<T> implements
          @Readonly List<@Readonly T> { ... }
//Thrown exception declaration
      void monitorTemperature() throws
          @Critical TemperatureException { ... }

Predefined Annotations

A set of annotation types are predefined in the Java SE API. Some annotation types are used by the Java compiler, and some apply to other annotations. These are called meta annotations.

True Annotations

Meta Annotations

Annotations DOC

Read next: Packages