Java › Annotations

What are Java's meta-annotations (@Retention, @Target, @Documented, @Inherited), and what does each control?

Intermediate

Answer

@Retention controls how long the annotation persists (SOURCE/CLASS/RUNTIME); @Target restricts which element types it can be applied to; @Documented causes the annotation to appear in generated Javadoc for annotated elements; @Inherited allows a class-level annotation to be automatically inherited by subclasses (only applies to annotations on classes, not methods/fields), letting a subclass be treated as if it also carries the annotation without redeclaring it.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Documented
public @interface Auditable { }

@Auditable
public class BaseEntity { }

public class Order extends BaseEntity { }  // inherits @Auditable automatically via reflection checks
Real-world example An auditing framework marks a base entity class with a custom @Inherited @Auditable annotation, and reflection-based checks on any subclass (like Order extends BaseEntity) correctly detect the annotation as present even though Order itself never explicitly declares it.

Common follow-ups: Why does @Inherited only work for class-level annotations, not methods or fields?;What's a scenario where you'd deliberately choose CLASS retention instead of RUNTIME or SOURCE?