Sitemap

Member-only story

Spring: Annotations, Retention Policies and Reflection

6 min readApr 10, 2025

Okay, let’s break down Retention Policies, Annotation Processors, and Reflection in Java, and then explore powerful use cases, especially combining annotations and reflection.

1. Annotations and Retention Policies@Retention:

What are Annotations? Annotations (@Override, @Deprecated, @SuppressWarnings, or custom ones like @MyAnnotation) are a form of metadata. They provide information about the code element (class, method, field, parameter, etc.) they are attached to, but they don't directly affect the operation of the code itself. Think of them as labels or tags.

What is a retention policy? The @Retention meta-annotation (an annotation applied to an annotation definition) specifies how long the annotation information should be kept. It determines whether the annotation is available only in the source code, compiled into the .class file, or available to the Java Virtual Machine (JVM) at runtime.

RetentionPolicy Enum Values:

RetentionPolicy.SOURCE:

The annotation is only kept in the source code (.java file).

It’s discarded by the compiler and not present in the compiled bytecode (.classfile) or available at runtime.

Mohit Bajaj
Mohit Bajaj

Responses (1)