Annotation values
- Java course
- Advanced
- Lesson 34/82
- 5 min
Learn annotation parameters and default values.
The value() element and shorthand
If an annotation has a single element named value(), you can give the value without its name: @Review("good") equals @Review(value = "good"). This shorthand works only when a single element is supplied.
When you supply multiple elements, naming them is required: @Cache(seconds = 60, region = "fast"). Here the order of seconds and region does not matter; the compiler matches by name. This flexibility keeps settings readable.
Array-typed elements
An element may be an array such as a String array: String[] tags();. When applied, even a single value is written in braces: @Tags({"a"}). Multiple values are comma-separated: @Tags({"a", "b"}).
The single-element rule still applies; if the element is named value and you give one value you can drop the braces: @Tags("a"). Array elements are common in code generation and configuration frameworks.
Practice Define and apply the Cache annotation
Define an @interface Cache with int seconds() default 30 and String region() default "primary". Apply @Cache(seconds = 60, region = "fast") to a load method. In main, print Cache set with System.out.println.
Starter code
// Define the Cache annotation
// Apply Cache to the load method
// Print to the screen in mainSample solution
@interface Cache {
int seconds() default 30;
String region() default "primary";
}
class Service {
@Cache(seconds = 60, region = "fast")
void load() { }
}
public class CacheDemo {
public static void main(String[] args) {
System.out.println("Cache set");
}
}Expected output
Cache set
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When you give an annotation a second element besides value, how must you write it?
- By writing only the value
- By naming each element explicitly Correct answer
- By using default
- By separating values in order
Explanation: With multiple elements each one is named explicitly.
2 Match the element writing forms
| Term | Meaning |
|---|---|
@Review("good") |
Single value shorthand |
@Cache(seconds = 60) |
Named element |
@Tags({"a","b"}) |
Array element |
String role() default "x" |
Default value |
3 Complete the named element application
@Cache(seconds = ____, region = "fast")
@Cache(seconds = 60, region = "fast")
Explanation: An int element takes an unquoted number.