Back to results for “Design Patterns in Java”
Java › Annotations

How do you create a custom annotation in Java, and what role do @Retention and @Target play?

Intermediate

Answer

A custom annotation is defined using @interface; @Retention specifies how long the annotation is retained (SOURCE, CLASS, or RUNTIME -- with RUNTIME needed if you want to read it via reflection), and @Target restricts which code elements (METHOD, TYPE, FIELD, etc.) the annotation can legally be applied to, both themselves being meta-annotations that configure your custom annotation's behavior.
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Loggable {
    String value() default "";
}

public class Service {
    @Loggable("critical operation")
    public void process() { }
}
Real-world example A team defines a custom @Loggable annotation with RUNTIME retention and METHOD target, letting an AOP-style interceptor read this annotation via reflection at runtime to automatically wrap annotated methods with logging behavior, without modifying each method's implementation.

Common follow-ups: What happens if you try to apply an annotation to an element type not listed in @Target?;Why would you ever choose SOURCE or CLASS retention over RUNTIME?