ElementType.CONSTRUCTOR: Annotating Constructors
What you'll learn: How to restrict your custom annotation to constructor declarations using ElementType.CONSTRUCTOR.
Core Idea
When you specify ElementType.CONSTRUCTOR in your annotation's @Target, you're telling the compiler: "This annotation can only be placed on constructors." Just as you've restricted annotations to classes (TYPE), fields (FIELD), methods (METHOD), or parameters (PARAMETER), you can now target constructors specifically.
This is particularly useful when you want to mark constructors for special processing—perhaps for dependency injection frameworks, object initialization tracking, or build pattern validation.
Syntax
import java.lang.annotation.*;
@Target(ElementType.CONSTRUCTOR)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidateOnConstruction {
String message() default "Validating...";
}
Using the Annotation
public class User {
private String name;
@ValidateOnConstruction(message = "Creating new user")
public User(String name) {
this.name = name;
}
@ValidateOnConstruction
public User() {
this.name = "Anonymous";
}
}
The annotation applies only to the constructor declaration itself. You cannot place @ValidateOnConstruction on a method, field, or class—the compiler will reject it.
Why Constructor-Specific Annotations?
Constructor annotations are valuable for frameworks that need to identify how objects should be instantiated. For example, an injection framework might look for @Inject on constructors to determine which constructor to call, or a serialization library might mark certain constructors as preferred for deserialization.
Key Takeaway: ElementType.CONSTRUCTOR restricts your annotation to constructor declarations only, enabling targeted metadata for object instantiation and initialization logic.