Deep Dive into Java Annotations
Meta-Annotations
Meta-annotations are annotations that apply to other annotations. Java provides several built-in meta-annotations:
@Retention - Specifies how long annotations are retained:
@Retention(RetentionPolicy.RUNTIME) // Available via reflection
@Retention(RetentionPolicy.CLASS) // In bytecode, not at runtime (default)
@Retention(RetentionPolicy.SOURCE) // Discarded after compilation
@Target - Restricts where an annotation can be applied:
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface MyAnnotation { }
// All possible ElementType values:
// TYPE (class, interface, enum), FIELD, METHOD, PARAMETER,
// CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE,
// TYPE_PARAMETER, TYPE_USE, MODULE, RECORD_COMPONENT
@Documented - Includes annotation in Javadoc:
@Documented
@interface Author {
String name();
}
@Inherited - Allows annotation inheritance from superclass:
@Inherited
@interface InheritableAnnotation { }
@InheritableAnnotation
class Parent { }
class Child extends Parent { } // Child inherits the annotation
@Repeatable - Allows multiple instances of the same annotation:
@Repeatable(Authors.class)
@interface Author {
String name();
}
@interface Authors {
Author[] value();
}
@Author(name = "Alice")
@Author(name = "Bob")
class Book { }
Annotation Elements and Constraints
Annotation elements follow specific rules:
public @interface ComplexAnnotation {
// Allowed element types:
String stringValue();
int intValue() default 42;
Class<?> classValue();
DayOfWeek enumValue();
Override annotationValue();
String[] arrayValue();
// Not allowed: Object, List, Map, custom objects
}
Elements must be:
- Primitives (int, long, double, etc.)
- String
- Class
- Enum
- Another annotation
- Arrays of the above types
Processing Annotations at Runtime
Using reflection to read annotations:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Benchmark {
int iterations() default 1;
}
public class AnnotationProcessor {
@Benchmark(iterations = 1000)
public void performanceTest() {
// Method implementation
}
public static void processAnnotations(Object obj) {
Class<?> clazz = obj.getClass();
for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(Benchmark.class)) {
Benchmark benchmark = method.getAnnotation(Benchmark.class);
System.out.println("Running " + method.getName() +
" for " + benchmark.iterations() + " iterations");
// Execute the method
try {
for (int i = 0; i < benchmark.iterations(); i++) {
method.invoke(obj);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Compile-Time Annotation Processing
Java provides an API for processing annotations during compilation:
@SupportedAnnotationTypes("com.example.GenerateBuilder")
@SupportedSourceVersion(SourceVersion.RELEASE_17)
public class BuilderProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(GenerateBuilder.class)) {
// Generate code, validate, or perform other compile-time tasks
generateBuilderClass(element);
}
return true;
}
private void generateBuilderClass(Element element) {
// Use JavaPoet or similar to generate source code
}
}
Type Annotations (Java 8+)
Type annotations can be applied anywhere a type is used:
@Target(ElementType.TYPE_USE)
@interface NonNull { }
@Target(ElementType.TYPE_USE)
@interface Nullable { }
public class TypeAnnotationExample {
@NonNull String name;
List<@NonNull String> items;
public void process(@Nullable String input) {
@NonNull String local = "value";
String @NonNull [] array = new String[5];
}
// Generic type parameters
public <@NonNull T> void genericMethod(T param) { }
}
Functional Annotations
@FunctionalInterface - Ensures an interface has exactly one abstract method:
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
// Can have default and static methods
default int add(int a, int b) {
return calculate(a, b);
}
}
Container Annotations Pattern
Before @Repeatable (pre-Java 8):
@interface Schedule {
String day();
String time();
}
@interface Schedules {
Schedule[] value();
}
@Schedules({
@Schedule(day = "Monday", time = "9:00"),
@Schedule(day = "Friday", time = "15:00")
})
class Meeting { }
Annotation Inheritance Behavior
Annotations are not inherited by default, except with @Inherited:
@Inherited
@interface InheritedAnno { }
@interface NotInheritedAnno { }
@InheritedAnno
@NotInheritedAnno
class Parent { }
class Child extends Parent { }
// Child has @InheritedAnno but not @NotInheritedAnno
// Method annotations are NEVER inherited
class Parent2 {
@Override
public String toString() { return "parent"; }
}
class Child2 extends Parent2 {
public String toString() { return "child"; } // No @Override inherited
}
Performance Considerations
Reflection-based annotation processing has overhead:
// Expensive - avoid in hot paths
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
// Process annotation
}
// Better - cache annotation data during initialization
public class AnnotationCache {
private final Map<Method, MyAnnotation> cache = new HashMap<>();
public void initialize(Class<?> clazz) {
for (Method method : clazz.getDeclaredMethods()) {
MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
if (anno != null) {
cache.put(method, anno);
}
}
}
}
Common Framework Usage Patterns
Spring Framework:
@Component
@Scope("prototype")
public class MyService {
@Autowired
private Repository repository;
@Transactional(isolation = Isolation.READ_COMMITTED)
@Cacheable(value = "users", key = "#id")
public User getUser(Long id) {
return repository.findById(id);
}
}
JUnit:
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class OrderedTests {
@Test
@Order(1)
@DisplayName("First test")
@Timeout(value = 2, unit = TimeUnit.SECONDS)
void firstTest() { }
@ParameterizedTest
@ValueSource(strings = {"hello", "world"})
void parameterizedTest(String value) { }
}
Annotations provide a powerful way to add metadata and behavior to Java code without cluttering the business logic, making them essential for modern Java development and framework design.