Java › Annotations
How do you create a custom annotation in Java, and what role do @Retention and @Target play?
IntermediateAnswer
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.