Java
Annotation values
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.
Exercise 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.
Show example 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");
}
}
Test yourself
-
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
- By using default
- By separating values in order
Show answer
By naming each element explicitly — With multiple elements each one is named explicitly.
-
Match the element writing forms
- @Review("good")
- Single value shorthand
- @Cache(seconds = 60)
- Named element
- @Tags({"a","b"})
- Array element
- String role() default "x"
- Default value
-
Complete the named element application
@Cache(seconds = ____, region = "fast")
Show answer
@Cache(seconds = 60, region = "fast")
Next lesson: Annotations via reflection