Difference Between @Retention and @Target Annotations
@Retention and @Target are both meta-annotations in Java used to define the characteristics of custom annotations. However, they serve different purposes:
1. @Retention Annotation
- Purpose: Specifies how long the annotation should be retained and available for use.
- Values:
RetentionPolicy.SOURCE: The annotation is discarded by the compiler and not included in the bytecode. It is only available in the source code.RetentionPolicy.CLASS: The annotation is included in the bytecode but not available at runtime. It can be read by the compiler but not used by reflection.RetentionPolicy.RUNTIME: The annotation is retained in the bytecode and is available at runtime. It can be accessed via reflection.
Example:
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) // Available at runtimepublic @interface MyAnnotation {
String value();
}
2. @Target Annotation
- Purpose: Specifies where the annotation can be applied (its target).
- Values:
ElementType.TYPE: Can be applied to classes, interfaces, or enums.ElementType.FIELD: Can be applied to fields (variables).ElementType.METHOD: Can be applied to methods.ElementType.PARAMETER: Can be applied to method parameters.ElementType.CONSTRUCTOR: Can be applied to constructors.ElementType.LOCAL_VARIABLE: Can be applied to local variables.ElementType.ANNOTATION_TYPE: Can be applied to other annotations.
Example:
import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.METHOD) // Can only be applied to methodspublic @interface MyMethodAnnotation {
String description();
}
Conclusion
- Use
@Retentionto control the lifecycle and availability of your annotation. - Use
@Targetto specify the contexts in which your annotation can be applied.