Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Java annotations: targets, retention, repetition, and reflection

In Java SE 21, an annotation declaration defines its data, where it may appear, and whether it is visible at run time. Learn how reflection reads that metadata, how repeated annotations are inherited, and how to scope unchecked-warning suppression.

Version: Java SE 21

Syntax

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR})
@interface Marker {}

@Target({ElementType.FIELD, ElementType.METHOD})
@interface MemberMarker {}

@Inherited
@Repeatable(Tags.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Tag { String value(); }

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Tags { Tag[] value(); }

Consumer<? super Integer> subscriber = new Consumer<Number>() {
    @Override public void accept(Number value) { System.out.println(value); }
};
Class<?> type = String.class;
Object payload = List.of("ok");
@SuppressWarnings("unchecked")
List<String> names = (List<String>) payload;

@interface declares an annotation interface. String value(); defines an element, and @Tag("core") is shorthand for @Tag(value = "core"). The Target meta-annotation from java.lang.annotation controls where an annotation may appear. @Target(ElementType.TYPE/FIELD/CONSTRUCTOR) is descriptive shorthand, not Java syntax: write @Target({ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR}). ElementType.TYPE covers class and interface declarations, not uses of a type (TYPE_USE). ElementType.FIELD/METHOD means two constants: ElementType.FIELD for fields and ElementType.METHOD for methods; constructors have a separate target.

Retention controls lifetime: SOURCE stays out of the class file, the default CLASS is recorded but not exposed by runtime reflection, and @Retention(RetentionPolicy.RUNTIME) makes the example's annotations reflectively available. Annotations on declarations of local variables and lambda parameters are exceptions: they are not stored in the class file. A class literal such as Base.class gives a Class<Base> object; Class<?> accepts it without exposing the specific type argument. ConfigKey, Init, Component, and Inject are custom metadata. Without code that interprets them, they do not configure, invoke, or inject anything.

@Repeatable(Tags.class) lets you write @Tag more than once at the same site. The compiler packages repeats in a container with Tag[] value(); any other container elements must have defaults. The container needs at least as long a retention and compatible targets; the example uses identical targets. If Tag has @Inherited, the container must have it too. getAnnotationsByType(Tag.class) unpacks the container and, because of Inherited, searches superclasses if a class has no tags of its own. It does not merge tags across levels, search interfaces, or inherit annotations on methods or fields. getDeclaredAnnotationsByType also unpacks containers but does not search superclasses; getAnnotation does not unpack containers.

new Consumer<Number>() { ... } declares and instantiates an anonymous class. @Override lets the compiler check that accept(Number) implements the interface method rather than accidentally overloading it. Java 21 also permits override-equivalent signatures of public Object methods and explicit record component accessors.

Consumer<? super Integer> accepts a consumer of Integer or one of its supertypes, such as Number or Object, and lets you pass it an Integer. The unbounded wildcard ?, as in Consumer<?>, leaves the type argument unknown, so you cannot pass it a non-null Integer. @SuppressWarnings("unchecked") silences the compiler warning; it neither checks list element types nor prevents ClassCastException. Avoid unnecessary casts; if a cast is justified, suppress the warning on the smallest declaration where suppression works.

Examples

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import java.util.function.Consumer;

public class Demo {
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.FIELD)
    @interface ConfigKey { String value(); }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface Init {}

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @interface Component {}

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD, ElementType.CONSTRUCTOR})
    @interface Inject {}

    @Inherited
    @Repeatable(Tags.class)
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @interface Tag { String value(); }

    @Inherited
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @interface Tags { Tag[] value(); }

    @Component
    @Tag("core")
    @Tag("fast")
    static class Base {
        @ConfigKey("port") final int port = 8080;
        boolean started;

        @Inject Base() {}
        @Init void start() { started = true; }
    }

    static class Child extends Base {}

    static void publish(Consumer<? super Integer> subscriber) {
        subscriber.accept(21);
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        Class<?> type = Base.class;
        Base service = new Base();
        var field = type.getDeclaredField("port");
        System.out.println("Config: " + field.getAnnotation(ConfigKey.class).value());
        boolean before = service.started;
        var method = type.getDeclaredMethod("start");
        if (method.isAnnotationPresent(Init.class)) {
            method.invoke(service);
        }
        System.out.println("Started: " + before + " -> " + service.started);
        System.out.println("Component/Inject: " + type.isAnnotationPresent(Component.class)
                + "/" + type.getDeclaredConstructor().isAnnotationPresent(Inject.class));

        Tag[] tags = Child.class.getAnnotationsByType(Tag.class);
        int declared = Child.class.getDeclaredAnnotationsByType(Tag.class).length;
        System.out.println("Tags: " + tags[0].value() + ", " + tags[1].value()
                + "; declared: " + declared);

        publish(new Consumer<Number>() {
            @Override public void accept(Number value) {
                System.out.println("Subscriber: " + value);
            }
        });

        Object payload = List.of("ok"); // This list is known here to contain only strings.
        @SuppressWarnings("unchecked")
        List<String> names = (List<String>) payload;
        System.out.println("Cast: " + names.get(0));
    }
}

Result

Config: port
Started: false -> true
Component/Inject: true/true
Tags: core, fast; declared: 0
Subscriber: 21
Cast: ok

`started` changes only when `method.invoke(service)` is explicitly called. `Child` reads two tags from `Base` even though it declares none. The cast is justified here by the list's known origin in `List.of("ok")`, not by `@SuppressWarnings`.

Related lessons

  • Java · Lesson 44 · Advanced · Version: 2
  • Java · Lesson 54 · Advanced · Version: 2
  • Java · Lesson 58 · Advanced · Version: 2
  • Java · Lesson 59 · Advanced · Version: 2

Sources