Retention and Target
- Java course
- Advanced
- Lesson 33/82
- 5 min
Learn @Retention and @Target meta-annotations.
Lifetime with @Retention
The @Retention meta-annotation decides how long an annotation is kept. It takes three values: SOURCE stays only in source (compiler discards it); CLASS is written to the class file but not visible at runtime (default); RUNTIME can be read by reflection at runtime.
Example: @Retention(RetentionPolicy.RUNTIME). If you want to read your annotation with reflection you must choose RUNTIME; otherwise it disappears at runtime.
Where to apply with @Target
The @Target meta-annotation restricts which elements an annotation can be applied to. Its values come from the ElementType enum: TYPE class/interface, METHOD method, FIELD field, PARAMETER parameter.
Example: @Target(ElementType.METHOD) allows only methods. If you put the annotation in the wrong place the compiler errors. Multiple places use an array: @Target({ElementType.TYPE, ElementType.METHOD}).
Practice Give retention and target to the Log annotation
Define an @interface Log. Add @Retention(RetentionPolicy.RUNTIME) and @Target(ElementType.TYPE) above it. In main, print Log defined with System.out.println.
Starter code
// Define the Log annotation
// Add Retention and Target
// Print to the screen in mainSample solution
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Log { }
public class LogDemo {
public static void main(String[] args) {
System.out.println("Log defined");
}
}Expected output
Log defined
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the retention value
@Retention(RetentionPolicy.____)
@Retention(RetentionPolicy.RUNTIME)
Explanation: RUNTIME makes the annotation readable at runtime.
2 Which retention is required to read an annotation with reflection at runtime?
- RetentionPolicy.RUNTIME Correct answer
- RetentionPolicy.SOURCE
- RetentionPolicy.CLASS
- ElementType.TYPE
Explanation: RUNTIME annotations are read by reflection; SOURCE is lost in the compiler.
3 Match the retention values
| Term | Meaning |
|---|---|
SOURCE |
Source code only |
CLASS |
Class file (default) |
RUNTIME |
Runtime |
FIELD |
An ElementType value |