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

Use Cases for CLASS Retention

Understand when CLASS retention is useful, including bytecode manipulation and tooling scenarios.

Use Cases for CLASS Retention

What you'll learn: You'll discover practical scenarios where RetentionPolicy.CLASS makes sense, even though these annotations aren't available at runtime.

Understanding the CLASS Retention Sweet Spot

Remember that CLASS retention means annotations are recorded in the .class file but aren't loaded into the JVM at runtime. This might seem useless at first—why keep them if you can't see them with reflection?

The answer: bytecode manipulation and compile-time tooling.

When CLASS Retention Shines

Bytecode Analysis Tools

Tools that read .class files directly (without running the code) can use these annotations. Think of static analyzers, code quality checkers, or dependency scanners that examine your compiled code looking for patterns or issues.

@Retention(RetentionPolicy.CLASS)
public @interface Nullable {
}

A static analyzer could read @Nullable from bytecode to warn about potential null pointer exceptions—without needing runtime reflection.

Bytecode Transformation Frameworks

Frameworks like ASM or ByteBuddy can inject code based on CLASS-retained annotations during the build process. They modify your .class files after compilation but before deployment.

Library Internal Use

Some libraries use CLASS retention for annotations that guide build-time processing but aren't needed once the application runs. This keeps runtime overhead minimal while still providing compile-time metadata.

The Default Choice

CLASS is actually the default retention policy if you don't specify @Retention at all. This is a reasonable default because it's the "middle ground"—preserved through compilation but not cluttering runtime memory.

Key Takeaway: Use CLASS retention when your annotations support bytecode analysis tools, build-time processors, or static analyzers that work on compiled .class files rather than running applications—offering metadata persistence without runtime overhead.