Java › Annotations
How do annotations with elements (parameters) work, including default values and the special `value` element?
IntermediateAnswer
Annotation elements are declared as methods (with no body) inside the @interface, optionally given a default value via the default keyword; an element specifically named value gets special syntactic sugar, letting callers omit the value = prefix when it's the only element being set (@MyAnnotation("text") instead of @MyAnnotation(value = "text")) -- elements can be primitives, String, Class, enums, other annotations, or arrays of these types, but never arbitrary objects.
@Retention(RetentionPolicy.RUNTIME)
public @interface Endpoint {
String value(); // special "value" element
String method() default "GET";
int timeout() default 30;
}
@Endpoint("/users") // shorthand for value = "/users"
@Endpoint(value = "/users", method = "POST", timeout = 60) // full explicit form
public void handler() { }Real-world example A routing annotation defines value as the path (allowing the terse @Endpoint("/users") syntax for the common case) while method and timeout have sensible defaults, letting most usages stay concise while still supporting full customization when needed.