@Retention
is a meta-annotation, meaning it’s an annotation used to annotate other annotations.
It tells the compiler and JVM how long your annotation should be retained (kept).
✅ Why is @Retention
Important?
Not all annotations need to be available at runtime — some are only needed during compilation, others only during class file generation. @Retention
defines where the annotation will be “visible” or “kept”.
🔗 Possible Retention Policies
Retention | Meaning | Example Use Case |
---|---|---|
RetentionPolicy.SOURCE | Annotation exists only in source code, removed during compilation | @Override (compiler-only checks) |
RetentionPolicy.CLASS | Annotation exists in .class file, but not available at runtime | Internal tools (bytecode enhancement) |
RetentionPolicy.RUNTIME | Annotation exists in .class file and available via reflection at runtime | Frameworks like Spring, JPA (dynamic processing) |
📚 Example — Custom Annotation with Retention
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}
✅ This makes @LogExecutionTime
available at runtime, so you can read it using reflection.
🚀 Example Usage in a Class
public class Service {
@LogExecutionTime
public void process() {
// some work
}
}
🔎 Reading Annotation with Reflection
import java.lang.reflect.Method;
public class AnnotationProcessor {
public static void main(String[] args) throws Exception {
Method method = Service.class.getMethod("process");
if (method.isAnnotationPresent(LogExecutionTime.class)) {
System.out.println("@LogExecutionTime is present");
}
}
}
✅ This works because LogExecutionTime
is retained at runtime.
@Retention(RetentionPolicy.SOURCE)
public @interface DeveloperNote {
String value();
}
This annotation disappears after compilation.It’s useful for tools like Checkstyle, ErrorProne, or code generators.You cannot read @DeveloperNote
at runtime — it’s gone after compilation.
🔥 Summary Table
Retention | Kept in Source? | Kept in Class File? | Available at Runtime? | Example Annotation |
---|---|---|---|---|
SOURCE | ✔️ Yes | ❌ No | ❌ No | @Override , @SuppressWarnings |
CLASS | ✔️ Yes | ✔️ Yes | ❌ No | Internal processing tools |
RUNTIME | ✔️ Yes | ✔️ Yes | ✔️ Yes | @Entity , @Service , @Test |
🎯 When to Use What
Case | Recommended Retention |
---|---|
Compiler checks only (no runtime need) | SOURCE |
Annotation only for internal tooling, not for runtime reflection | CLASS |
Annotation used by frameworks at runtime (like Spring, JPA, JUnit) | RUNTIME |
💡 Pro Tip for Interviews
✅ Always say:
“The
@Retention
annotation controls how long an annotation is kept — source, class file, or runtime. Most framework annotations (like@Entity
or@Service
) useRUNTIME
, so they can be processed using reflection at runtime.”
✅ Also mention:
@Override
uses SOURCE — compiler only.- JPA annotations like
@Entity
use RUNTIME — required for reflection at runtime.