Annotations
Meta Annotations
Learn standard meta-annotations: @Retention, @Target, @Documented, @Inherited, and @Repeatable.
Interview: Focuses on @Inherited behavior across class hierarchies and implementing @Repeatable container structures.
Meta-annotations are annotations applied to other annotations during custom declaration. They define scope boundaries, document visibility, and inheritance behavior.
Core Idea
Meta-annotations configure the lifecycle and target elements of custom annotations.
Why It Matters
Applying Target and Retention constraints prevents developer errors like placing class annotations on parameters.
Interview Lens
Focuses on @Inherited limitations (only applies to class inheritance, not interfaces) and @Repeatable configurations.
Standard Meta-Annotations
@Retention: Defines how long the annotation is kept (SOURCE, CLASS, RUNTIME).@Target: Restricts where the annotation can be applied (e.g.ElementType.METHOD,TYPE,FIELD).@Inherited: Indicates that the annotation is inherited automatically by subclasses of the annotated class.@Repeatable: Allows applying the same annotation multiple times on the same element (introduced in Java 8). Requires a container annotation wrapper.
Code Walkthrough
This example demonstrates how to declare a repeatable custom annotation.
import java.lang.annotation.*;// 1. Declare Container annotation first @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface Roles { Role[] value(); }
// 2. Declare repeatable annotation pointing to Container @Repeatable(Roles.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Role { String value(); }
Interview-Relevant Information
Q: Does @Inherited work if placed on an interface?
Answer: No. @Inherited only affects class inheritance. If an interface is annotated with an inherited annotation, classes implementing that interface do NOT inherit the annotation. Similarly, annotated methods do not propagate annotations to overriding subclass methods.
Quick Checklist
What targets restrict annotations to classes? How do you implement a repeatable annotation? If yes, you understand meta-annotations.
Use Cases
Defining strict location constraints for framework tags.
Implementing multi-permission matching using repeatable roles.
Common Mistakes
Forgetting to apply @Retention(RetentionPolicy.RUNTIME) to annotations meant to be parsed at runtime (defaulting to CLASS retention, which excludes them).
Expecting @Inherited to work on interface implementations or method overrides.