Custom Annotations

Basic Java
≈ 2 min read

A custom annotation is a separate type

When an application needs its own metadata, you can declare a custom annotation. The @interface construct is used for this purpose. It creates a new annotation type that can then be applied in code.

public @interface Audit {
    String action();
}

The action() notation looks like a method here, but it describes an annotation element. A value must be supplied when the annotation is used.

@Audit(action = "CREATE")
void createUser() {
}

Default values

An element can define a default value. Then the annotation user supplies that value only when they want something different from the standard behavior.

public @interface Audit {
    String action();
    boolean enabled() default true;
}

If an annotation has a single element named value, its name may be omitted at the use site: @Label("admin") instead of @Label(value = "admin").

Which element types are allowed

Annotation elements cannot have arbitrary object types. Allowed types include primitives, String, Class, enum types, other annotation types, and arrays of those types. The value null is not allowed.

public @interface Retry {
    int attempts() default 3;
    Class<? extends Throwable> on();
}
Declaring an annotation is not enough. You still need to define who processes it and what it means for the application. On the next pages, we will configure the annotation's lifetime and allowed targets, then learn to read it through reflection.