Java.Core.Provide example where we need source retention

Source retention needed for static analysis tool, for ex.

Let’s walk through a practical example where @Retention(RetentionPolicy.SOURCE) is the best choice. This is typically used for compile-time annotations — annotations that are only useful to the compiler, linters, documentation tools, or static analysis tools, but have no purpose at runtime.


🔥 Example — @Todo Annotation (Source Retention)

Imagine you want to mark methods in your codebase that still need work — like a TODO note for developers. This is helpful during development and for static analysis tools, but it serves no purpose at runtime.

Define the Annotation

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

// Only exists in source code — disappears after compilation
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Todo {
    String message();
    String createdBy() default "Unknown";
    String priority() default "LOW";
}

Use the Annotation in Your Code

public class OrderService {

    @Todo(message = "Need to handle case where order is null", createdBy = "Stanley", priority = "HIGH")
    public void processOrder(Order order) {
        if (order == null) {
            // TODO: Handle null case (currently unhandled)
        }
    }
}

Why SOURCE Retention?

✅ This annotation only exists for developers and static analysis tools like:

  • Checkstyle
  • ErrorProne
  • Custom annotation processors

✅ It does not need to exist:

  • In the compiled .class file.
  • At runtime (your application logic doesn’t care about @Todo).

🚨 What Happens After Compilation?

The @Todo annotation:

  • Exists only in the source code.
  • Is discarded during compilation.
  • Is not present in the .class file.
  • Cannot be read with reflection.

📊 Why Not CLASS or RUNTIME?

RetentionReason to Avoid for @Todo
CLASSThere’s no reason for this to exist in the class file. It’s irrelevant after compilation.
RUNTIMEThe application does not need to reflect on @Todo at runtime — it’s purely for development process.

🔗 Where SOURCE Retention Makes Sense

Annotation TypeExample
Developer notes@Todo, @DeveloperNote
Compiler hints@SuppressWarnings, @Override
Documentation toolsCustom annotations that modify Javadoc output

💡 Pro Tip for Interviews

✅ If asked for a SOURCE retention use case, say:

“Annotations meant only for development and static analysis — like TODOs, developer warnings, or custom static checks — are perfect candidates for SOURCE retention.”

✅ Real-life analogy: @SuppressWarnings uses SOURCE because the compiler needs it, but your app at runtime doesn’t care about it.

This entry was posted in Без рубрики. Bookmark the permalink.