Junior — Middle
Can you explain what the RetentionPolicy annotation means in Java and how it affects the lifecycle of an annotation?
sobes.tech AI
Answer from AI
The @Retention annotation in Java specifies how long annotations are retained and available at runtime. It takes a value from the RetentionPolicy enum, which can be:
SOURCE— the annotation is only available in source code and is discarded by the compiler, not included in the bytecode.CLASS— the annotation is stored in the bytecode but not available at runtime (default).RUNTIME— the annotation is stored in the bytecode and available at runtime via reflection.
For example, if an annotation is marked with @Retention(RetentionPolicy.RUNTIME), it can be accessed through reflection during program execution, which is useful for frameworks and libraries that analyze annotations dynamically.
Example:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
@MyAnnotation("example")
public class Test {}
// At runtime, you can get the annotation like this:
MyAnnotation ann = Test.class.getAnnotation(MyAnnotation.class);
if (ann != null) {
System.out.println(ann.value());
}