Course contentsShow
← Java
Lesson 2433 of 2,87046. AnnotationsFree lesson

The @Retention Meta-Annotation

Learn how to use @Retention to specify the lifecycle of your custom annotations.

The @Retention Meta-Annotation

You'll learn how to use @Retention to control when your custom annotations are available during your program's lifecycle.

What Is @Retention?

When you create a custom annotation, you need to tell Java how long to keep it around. Should it disappear after compilation? Stick around in the .class file? Or remain available at runtime for reflection? The @Retention meta-annotation answers this question.

Think of retention like a concert ticket's validity period: some tickets are only good until you enter the venue (compile-time), some get stamped and stored (class file), and others remain scannable throughout the entire event (runtime).

How @Retention Works

You apply @Retention to your custom annotation declaration, passing it a RetentionPolicy value:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value();
}

The three retention policies are:

  • SOURCE: Annotation discarded after compilation (like @Override)
  • CLASS: Stored in .class files but not loaded by JVM (default)
  • RUNTIME: Available at runtime for reflection

Why It Matters

If you want to read your annotation at runtime using reflection (as you learned in the previous lessons), you must use RetentionPolicy.RUNTIME. Without it, your annotation won't be accessible via getAnnotation() or related methods, even though it exists in your source code.

Key Takeaway: The @Retention meta-annotation controls your custom annotation's lifecycle—use RetentionPolicy.RUNTIME when you need reflection access, SOURCE for compile-time checks only, and CLASS for bytecode-level tools.