Java: Annotations

public @interface TheAnnotation{
	int aConstant = 123;
	String element1();
	String element2();
	String element3() default “DefaultValue”;
}

// invoked by...
@TheAnnotation(element1 = “1”, element2 = “2”);

If there is only one element specified and it is called “value”, the name can be omitted

@TheAnnotation2(“MustBeDefinedAsValue”);

Annotation elements can only be:

  • Primitive types (int but not Integer)
  • String
  • Class
  • Enum
  • Annotation
  • Array (one dimensional)

Java includes many predefined annotations.

Annotation-specific annotations (used in defining annotations) include

  • @Target: where in code can the annotation be used?
  • @Retention: how far into the compilation/execution process is the annotation retained?
  • @Documented: visible in the javadoc
  • @Inherited: Inherited by subclasses?
  • @Repeatable: multiple instances of the same annotation permitted?