What You'll Learn
You'll learn how annotation elements are declared as abstract methods and automatically become attributes when the annotation is applied.
Annotation Elements Are Method Declarations
When you create a custom annotation, you define its elements by declaring abstract methods inside the @interface. These methods don't have bodies—they simply specify what information the annotation can carry.
Each method you declare becomes an attribute that users must (or can) provide when applying your annotation. The method's return type determines what kind of value can be assigned to that element.
How It Works
Think of annotation elements like form fields: when you design a form, you specify what information should be collected (name, age, email). Similarly, when you declare methods in an annotation, you're defining what data the annotation can hold.
public @interface Author {
String name(); // Element: accepts a String
String date(); // Element: accepts a String
int version(); // Element: accepts an int
}
When someone uses your @Author annotation, they provide values for these elements:
@Author(name = "Alice", date = "2024-01-15", version = 2)
public class MyClass {
// ...
}
The method names (name, date, version) become the attribute names, and the return types determine what values are valid.
Valid Return Types
Annotation elements can only return:
- Primitives (
int,boolean, etc.) StringClassobjects- Enums
- Other annotations
- Arrays of any of the above
Key Takeaway: Annotation elements are declared as abstract methods without bodies—their names become attribute names, and their return types define what values the annotation can accept when used.