The syntax for creating an annotation is similar to an interface declaration, using the
@interface
keyword.
Inside the annotation body, you define methods (called elements or attributes) according to the following rules:
-
Method declarations must not have parameters or throw clauses.
-
Method return types are restricted to: primitives, String, Class, enum types, annotation types, and arrays of these types.
-
Methods can have default values using the
default
keyword.
-
If an annotation has only one element, it should be named
value
for convenience.
Example:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Annotation1 {
double value() default 10.0;
}
When an annotation has a single element named
value
, the element name can be omitted when using the annotation.
If a default value is provided and you want to use it, parentheses can be omitted entirely.
Example:
public class Test1Annotation1 {
@Annotation1 // Uses default value (10.0)
public Double myVar1;
@Annotation1(1.2) // Shorthand for value = 1.2
public Double myVar2;
@Annotation1(value = 1.3) // Explicit element name
public Double myVar3;
}
Annotations with no elements are called marker annotations and can be used without parentheses.