0Pricing
Java Academy · Lesson

Retention Policies and Target Types

Choose SOURCE, CLASS, or RUNTIME retention and restrict target elements with @Target.

The Three Retention Policies

SOURCE: discarded by the compiler (only useful to APT). CLASS: written to .class files, not available at runtime. RUNTIME: available via reflection. Most framework annotations use RUNTIME.

SOURCE Retention: Compile-Time Only

SOURCE annotations are processed by annotation processors and then discarded. @Override and @SuppressWarnings are SOURCE — they inform the compiler but are not in the .class file.

@Retention(RetentionPolicy.SOURCE)
public @interface GenerateBuilder {}
// APT generates a Builder class when it sees @GenerateBuilder
// The annotation itself disappears from the compiled output

All lessons in this course

  1. Defining Annotations: Elements and Defaults
  2. Retention Policies and Target Types
  3. Runtime Annotation Processing
  4. Compile-Time Annotation Processors
← Back to Java Academy