@Retention is a meta-annotation used to define how long a custom annotation should remain available during the application's lifecycle. It determines whether an annotation is retained only in source code, stored in the compiled class file, or accessible at runtime through reflection.
Key Points: • RetentionPolicy.SOURCE keeps the annotation only in source code and removes it during compilation. • RetentionPolicy.CLASS stores the annotation in the bytecode but makes it unavailable at runtime. This is the default retention policy. • RetentionPolicy.RUNTIME preserves the annotation at runtime, allowing frameworks and reflection-based tools to read and process it.
Example: Frameworks such as Spring, Hibernate, and JUnit rely on annotations with RUNTIME retention because they inspect annotations through reflection while the application is running.
Code Example:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface Developer {
String name();
}
@Developer(name = "John")
class Employee {
}
public class Main {
public static void main(String[] args) {
Developer annotation =
Employee.class.getAnnotation(
Developer.class);
System.out.println(
annotation.name());
}
}Interview Tip: A concise interview answer is: @Retention specifies how long an annotation should be retained in Java. SOURCE keeps it only in source code, CLASS stores it in bytecode, and RUNTIME makes it available during execution through reflection, which is commonly used by frameworks and libraries.