CKTIS / Java
Anotaciones en Java: destinos, retención, repetición y reflexión
En Java SE 21, la declaración de una anotación define sus datos, dónde puede aparecer y si es visible en tiempo de ejecución. Aprende a leer esos metadatos por reflexión, a distinguir lo declarado de lo heredado y a limitar la supresión de avisos.
Versión: Java SE 21
Sintaxis
@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 una interfaz de anotación. String value(); define un elemento y @Tag("core") abrevia @Tag(value = "core"). La metaanotación Target de java.lang.annotation fija los lugares permitidos. @Target(ElementType.TYPE/FIELD/CONSTRUCTOR) es una abreviatura descriptiva, no sintaxis Java: escribe @Target({ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR}). ElementType.TYPE abarca declaraciones de clases e interfaces, no usos de un tipo (TYPE_USE). ElementType.FIELD/METHOD representa dos constantes: ElementType.FIELD para campos y ElementType.METHOD para métodos. Los constructores tienen un destino propio.
Retention controla cuánto se conserva la anotación: SOURCE no llega al archivo de clase, CLASS es el valor predeterminado y se registra sin quedar expuesto por reflexión en ejecución, y @Retention(RetentionPolicy.RUNTIME) permite leer por reflexión las anotaciones del ejemplo. Las anotaciones de declaración de variables locales y parámetros de lambda son excepciones: no se guardan en el archivo de clase. El literal de clase Base.class da un objeto Class<Base>; Class<?> lo acepta sin exponer el argumento de tipo concreto. ConfigKey, Init, Component e Inject son metadatos propios; sin código que los interprete, no configuran, invocan ni inyectan nada.
@Repeatable(Tags.class) permite escribir varios @Tag en el mismo lugar. El compilador agrupa las repeticiones en un contenedor con Tag[] value(); los demás elementos del contenedor necesitan valores predeterminados. El contenedor debe tener una retención al menos igual y destinos compatibles; en el ejemplo los destinos son idénticos. Si Tag lleva @Inherited, el contenedor también debe llevarla. getAnnotationsByType(Tag.class) extrae las anotaciones del contenedor y, gracias a Inherited, busca en las superclases si la clase no tiene etiquetas propias. No combina etiquetas de distintos niveles, no consulta interfaces ni hereda anotaciones de métodos o campos. getDeclaredAnnotationsByType también abre el contenedor, pero no busca en superclases; getAnnotation no lo abre.
new Consumer<Number>() { ... } declara e instancia una clase anónima. @Override permite al compilador comprobar que accept(Number) implementa el método de la interfaz en lugar de sobrecargarlo por error. Java 21 también admite firmas equivalentes a efectos de sobrescritura a las de métodos públicos de Object y accesores explícitos de componentes de un record.
Consumer<? super Integer> admite un consumidor de Integer o de un supertipo como Number u Object, y permite pasarle un Integer. El comodín sin cota ?, como en Consumer<?>, deja el argumento de tipo indeterminado, por lo que no permite pasarle un Integer no nulo. @SuppressWarnings("unchecked") silencia el aviso del compilador, pero no comprueba los tipos de los elementos de la lista ni evita ClassCastException. Evita las conversiones de tipo innecesarias; si una está justificada, suprime el aviso en la declaración más pequeña donde sea efectivo.
Ejemplos
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` solo cambia al llamar explícitamente a `method.invoke(service)`. `Child` lee dos etiquetas de `Base` aunque no declara ninguna. La conversión de tipo se justifica por el origen conocido de la lista en `List.of("ok")`, no por `@SuppressWarnings`.
Lecciones relacionadas
- Java · Lección 44 · Avanzado · Versión: 2
- Java · Lección 54 · Avanzado · Versión: 2
- Java · Lección 58 · Avanzado · Versión: 2
- Java · Lección 59 · Avanzado · Versión: 2
Fuentes
- Java SE 21 Language Specification §9.6 — Annotation Interfaces and Predefined Annotation Interfaces
- Java SE 21 Language Specification §9.7.5 — Multiple Annotations of the Same Interface
- Java SE 21 API — ElementType
- Java SE 21 API — RetentionPolicy
- Java SE 21 API — AnnotatedElement
- Java SE 21 API — SuppressWarnings
- Java SE 21 Language Specification §4.5.1 — Type Arguments of Parameterized Types
- Java SE 21 Language Specification §15.8.2 — Class Literals
- Java SE 21 Language Specification §15.9.5 — Anonymous Class Declarations