Enum-Valued Elements for Controlled Options
You'll learn how to use enum types in custom annotations to restrict element values to a fixed set of meaningful constants.
The Core Idea
Sometimes when designing annotations, you want users to choose from a limited set of options—not just any string or number. By declaring an annotation element with an enum type, you force users to pick from predefined constants, making your API safer and more self-documenting.
Think of it like a restaurant menu: instead of letting customers write whatever they want on an order form (strings), you give them a fixed list of dishes to choose from (enum constants). This prevents typos and invalid choices.
How It Works
When you create a custom annotation, declare an element whose return type is an enum. Users must then provide one of that enum's constants when applying the annotation:
// First, define your enum
enum Priority {
LOW, MEDIUM, HIGH, CRITICAL
}
// Use it as an annotation element type
@interface Task {
Priority priority();
String description();
}
// Apply it with a specific enum constant
@Task(priority = Priority.HIGH, description = "Fix security bug")
public void urgentFix() {
// method code
}
You cannot write @Task(priority = "HIGH") with a string—the compiler enforces that you use Priority.HIGH.
Why This Matters
Enum-valued elements provide compile-time safety. The IDE autocompletes valid options, typos are impossible, and refactoring tools can rename enum constants safely across your entire codebase. It's far better than using strings like "high" or "HIGH" where variations cause bugs.
Key Takeaway: Use enum types for annotation elements when you need controlled, type-safe choices from a predefined set of constants—the compiler will prevent invalid values and make your annotations self-documenting.