ElementType.LOCAL_VARIABLE: Annotating Local Variables
What You'll Learn
You'll learn how to apply custom annotations to local variable declarations inside method bodies using ElementType.LOCAL_VARIABLE.
Understanding Local Variable Annotations
When you specify @Target(ElementType.LOCAL_VARIABLE), your annotation can be placed on variable declarations within methods, constructors, or initializer blocks. These annotations exist only at the source level—they're typically used by code analysis tools, IDEs, or compile-time processors.
Important limitation: Even if you set @Retention(RetentionPolicy.RUNTIME), local variable annotations are not retained at runtime. They vanish after compilation because local variables don't exist in bytecode the same way fields or methods do. This makes them primarily useful for compiler checks and development-time tooling.
Defining a Local Variable Annotation
import java.lang.annotation.*;
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.LOCAL_VARIABLE)
public @interface NonNull {
}
Using the Annotation
public void processData(String input) {
@NonNull String sanitized = input.trim();
@NonNull int count = 0;
for (int i = 0; i < sanitized.length(); i++) {
count++;
}
System.out.println("Processed: " + count);
}
The @NonNull annotation helps static analysis tools verify that sanitized should never be null, catching potential bugs during development.
Think of It This Way
Local variable annotations are like sticky notes you place on variables while coding—they help tools understand your intent and catch mistakes, but they're removed before the program runs in production.
Key Takeaway: ElementType.LOCAL_VARIABLE restricts annotations to local variables inside methods; these annotations serve development-time purposes and aren't available via reflection at runtime, even with RUNTIME retention.