ElementType.PARAMETER: Annotating Method Parameters
You'll learn how to apply custom annotations to the formal parameters of methods and constructors using ElementType.PARAMETER.
What This Target Type Means
Just as you can annotate classes, fields, and methods, Java lets you annotate individual parameters in method and constructor signatures. When you declare an annotation with @Target(ElementType.PARAMETER), you're specifying that this annotation can only be placed before parameter declarations.
Think of it like labeling each ingredient in a recipe differently—one might be marked "organic," another "optional," and a third "gluten-free." Each parameter gets its own metadata tag.
Basic Syntax
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface NotNull {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface MaxLength {
int value();
}
Applying Parameter Annotations
public class UserService {
public void createUser(@NotNull String username,
@MaxLength(50) String email,
@NotNull String password) {
// Implementation
}
public UserService(@NotNull DatabaseConnection connection) {
// Constructor with annotated parameter
}
}
Each parameter can have its own annotation, allowing validation frameworks, dependency injection tools, or custom processors to examine and act on parameter-specific metadata at runtime.
Why Annotate Parameters?
Parameter annotations enable frameworks to validate input, inject dependencies based on parameter metadata, or enforce contracts. They're heavily used in JAX-RS REST APIs, Spring's @RequestParam, and validation libraries like Bean Validation.
Key Takeaway: ElementType.PARAMETER lets you attach metadata to individual method and constructor parameters, enabling fine-grained introspection and processing of each argument independently.