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

RetentionPolicy.CLASS Explained

Learn CLASS retention: annotations recorded in class files but not available via reflection at runtime.

RetentionPolicy.CLASS Explained

What you'll learn: You'll understand CLASS retention—annotations that persist in bytecode but vanish before your program runs.


When you annotate code with @Retention(RetentionPolicy.CLASS), you're telling the compiler: "Keep this annotation in the compiled .class file, but don't bother loading it into memory at runtime." This means the annotation survives compilation and can be read by bytecode analysis tools, but it won't be accessible via reflection when your program executes.

How CLASS Retention Works

Think of CLASS retention like writing a note on a product's packaging—it's there when the product ships, but gets thrown away before the customer uses it. The JVM reads the .class file, notices the annotation, and then discards it before your code can call getAnnotations() or isAnnotationPresent().

This is actually the default retention policy if you don't specify @Retention at all. Many developers use it accidentally without realizing their annotations disappear at runtime!

Why Use CLASS Retention?

  • Bytecode processors: Tools like ASM or ByteBuddy can read these annotations to modify or analyze compiled code
  • Build-time verification: Static analysis tools can check .class files without needing runtime overhead
  • Smaller runtime footprint: Since the JVM discards these annotations, your program uses slightly less memory

Unlike SOURCE retention (which vanishes after compilation), CLASS annotations do make it into your JAR files—they're just invisible to reflection APIs.

Practical Context

You would use CLASS retention when you need information preserved for post-compilation tools but don't want to pay the runtime cost of loading annotation metadata. This strikes a balance between compile-time-only and full runtime availability.

Key Takeaway: CLASS retention keeps annotations in .class files for bytecode tools to read, but the JVM discards them before runtime reflection can access them.