Back to results for “Annotations”
Java › Annotations

How do annotations with elements (parameters) work, including default values and the special `value` element?

Intermediate

Answer

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.

Common follow-ups: What types are legal for annotation elements, and why can't you use an arbitrary POJO type?;How do array-typed elements with a single value get abbreviated syntactically?