Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / Java

Anotações em Java: alvos, retenção, repetição e reflexão

Em Java SE 21, a declaração de uma anotação define os seus dados, onde pode aparecer e se é visível em tempo de execução. Aprende a ler metadados por reflexão, a distinguir anotações declaradas de herdadas e a limitar a supressão de avisos.

Versão: Java SE 21

Sintaxe

@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 declara uma interface de anotação. String value(); define um elemento e @Tag("core") abrevia @Tag(value = "core"). A metaanotação Target de java.lang.annotation indica os locais permitidos. @Target(ElementType.TYPE/FIELD/CONSTRUCTOR) é uma abreviatura descritiva, não sintaxe Java: escreve @Target({ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR}). ElementType.TYPE abrange declarações de classes e interfaces, não utilizações de um tipo (TYPE_USE). ElementType.FIELD/METHOD indica duas constantes: ElementType.FIELD para campos e ElementType.METHOD para métodos. Os construtores têm um alvo próprio.

Retention controla a conservação: SOURCE não é guardado no ficheiro de classe, CLASS é o valor predefinido e fica registado no ficheiro, mas não fica acessível por reflexão em execução, e @Retention(RetentionPolicy.RUNTIME) torna acessíveis por reflexão as anotações do exemplo. As anotações de declaração de variáveis locais e de parâmetros de expressões lambda são exceções: não são guardadas no ficheiro de classe. O literal de classe Base.class dá um objeto Class<Base>; Class<?> aceita-o sem expor o argumento de tipo específico. ConfigKey, Init, Component e Inject são metadados personalizados; sem código que os interprete, não configuram, invocam nem injetam nada.

@Repeatable(Tags.class) permite escrever vários @Tag no mesmo local. O compilador agrupa as repetições num contentor com Tag[] value(); os restantes elementos precisam de valores predefinidos. O contentor tem de ter uma retenção pelo menos tão longa e alvos compatíveis; no exemplo, os alvos são iguais. Se Tag tiver @Inherited, o contentor também tem de a ter. getAnnotationsByType(Tag.class) extrai as anotações do contentor e, graças a Inherited, procura nas superclasses se a classe não tiver etiquetas próprias. Não junta etiquetas de vários níveis, não pesquisa interfaces nem herda anotações de métodos ou campos. getDeclaredAnnotationsByType também extrai as anotações do contentor, mas não pesquisa superclasses; getAnnotation não abre o contentor.

new Consumer<Number>() { ... } declara e instancia uma classe anónima. @Override permite ao compilador verificar se accept(Number) implementa o método da interface em vez de o sobrecarregar por engano. Java 21 também admite assinaturas equivalentes para efeitos de redefinição às de métodos públicos de Object e métodos de acesso explícitos a componentes de records.

Consumer<? super Integer> aceita um consumidor de Integer ou de um seu supertipo, como Number ou Object, e permite passar-lhe um Integer. O caráter universal sem limite ?, como em Consumer<?>, deixa o argumento de tipo desconhecido, pelo que não se pode passar um Integer diferente de null. @SuppressWarnings("unchecked") silencia o aviso do compilador, mas não verifica os tipos dos elementos da lista nem impede ClassCastException. Evita conversões de tipo desnecessárias; se uma for justificada, suprime o aviso na declaração mais pequena em que tal seja eficaz.

Exemplos

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));
    }
}

Resultado

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

`started` só muda quando `method.invoke(service)` é chamado explicitamente. `Child` lê duas etiquetas de `Base` sem declarar nenhuma. A conversão de tipo justifica-se pela origem conhecida da lista em `List.of("ok")`, não por `@SuppressWarnings`.

Lições relacionadas

  • Java · Lição 44 · Avançado · Versão: 2
  • Java · Lição 54 · Avançado · Versão: 2
  • Java · Lição 58 · Avançado · Versão: 2
  • Java · Lição 59 · Avançado · Versão: 2

Fontes