ElementType.FIELD: Annotating Fields
You'll learn how to use ElementType.FIELD to allow your custom annotations on class fields, including enum constants.
What Is FIELD Targeting?
When you create a custom annotation with @Target(ElementType.FIELD), you're declaring that the annotation can only be placed directly on field declarations. This includes instance variables, static variables, and even enum constants (which are technically static final fields).
Think of ElementType.FIELD as giving your annotation permission to "decorate" the data members of a class—the things that hold state.
How to Use ElementType.FIELD
Here's a simple example:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sensitive {
String reason() default "confidential";
}
Now you can apply @Sensitive to fields:
public class User {
@Sensitive
private String password;
@Sensitive(reason = "PII")
private String socialSecurityNumber;
private String username; // No annotation - public info
}
You cannot use @Sensitive on methods, classes, or other elements—only on fields.
Fields vs. Other Targets
Fields are distinct from local variables (which use ElementType.LOCAL_VARIABLE) and method parameters (which use ElementType.PARAMETER). FIELD specifically targets the class-level or instance-level variables declared inside a class body.
Practical Applications
Field annotations are commonly used for:
- Dependency injection (
@Inject,@Autowired) - Serialization control (
@JsonProperty,@Transient) - Validation rules (
@NotNull,@Max) - Security marking (like our
@Sensitiveexample)
Key Takeaway: Use @Target(ElementType.FIELD) to restrict your custom annotation to class fields and enum constants, enabling frameworks to process or validate field-level metadata at runtime or compile time.