CodeBlanks Logo Icon CodeBlanks

Retention and Target

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

Main.java
// Define the Log annotation
// Add Retention and Target
// Print to the screen in main

Sample solution

Main.java
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

Question
@Retention(RetentionPolicy.____)
Answer
@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

All lessons in Advanced