CKTIS / Java
Reading class annotations with reflection
Read repeatable annotations as an array and test for a marker annotation. Distinguish inherited lookup from lookup restricted to the class declaration.
Version: Java SE 21
Syntax
On java.lang.Class<T> (instance methods; Annotation is java.lang.annotation.Annotation):
<A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass)
boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
<A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass)
<A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass)
Class literals: Child.class has type Class<Child>; Tag.class has type Class<Tag>.
Example call: Child.class.getAnnotationsByType(Tag.class)The class literal Child.class gives you the Class<Child> object to inspect; Tag.class gives you the Class<Tag> object that identifies the annotation type to query. These are instance methods on Class: you do not create a Child object. To read class declaration annotations through reflection, give the annotation type @Retention(RetentionPolicy.RUNTIME).
In the pair Class.getAnnotationsByType/isAnnotationPresent, use getAnnotationsByType(Tag.class) when you need the annotations themselves. It returns a Tag[], or an empty array, not null, if there is no match. It unwraps the container specified by @Repeatable, preserving the order of entries in the container. If the queried type has @Inherited and the class has no match either directly or inside the container, the lookup follows superclasses, not interfaces. It does not merge matches across levels. getDeclaredAnnotationsByType also unwraps the container but only checks the class being inspected.
isAnnotationPresent(A.class) returns a boolean and is equivalent to getAnnotation(A.class) != null. It is useful for marker annotations, which have no elements. If there is no direct match and the queried type has @Inherited, it checks superclasses, not interfaces. It does not look inside a container, so repetitions found only in a container do not make the test true for the repeatable type. getDeclaredAnnotation checks only for a direct match on the class and returns null when none exists.
All the methods above that take an annotation type throw NullPointerException for a null argument. To test for at least one match including container entries, use getAnnotationsByType(Tag.class).length > 0.
Examples
import java.lang.annotation.*;
import java.util.Arrays;
public class AnnotationDemo {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@interface Flag {}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Repeatable(Tags.class)
@interface Tag { String value(); }
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@interface Tags { Tag[] value(); }
@Flag
@Tag("alpha")
@Tag("beta")
static class Base {}
static class Child extends Base {}
@Tag("local")
static class Local extends Child {}
public static void main(String[] args) {
System.out.println("Child tags: " + values(Child.class.getAnnotationsByType(Tag.class)));
System.out.println("Child declared tags: " + Child.class.getDeclaredAnnotationsByType(Tag.class).length);
System.out.println("Child flag: " + Child.class.isAnnotationPresent(Flag.class));
System.out.println("Child declared flag: " + (Child.class.getDeclaredAnnotation(Flag.class) != null));
System.out.println("Base Tag present: " + Base.class.isAnnotationPresent(Tag.class));
System.out.println("Local tags: " + values(Local.class.getAnnotationsByType(Tag.class)));
}
private static String values(Tag[] tags) {
return Arrays.stream(tags).map(Tag::value).toList().toString();
}
}Result
Child tags: [alpha, beta] Child declared tags: 0 Child flag: true Child declared flag: false Base Tag present: false Local tags: [local]
`Child` inherits `@Flag` and both `@Tag` instances but declares none of them. The two `@Tag` instances on `Base` are stored in the `@Tags` container, so testing presence for `Tag.class` on `Base` returns `false`. The `@Tag` on `Local` takes precedence over the inherited instances rather than being added to them.
Related lessons
- Java · Lesson 58 · Advanced · Version: 2
Sources
- Java SE 21 API — Class.getAnnotationsByType
- Java SE 21 API — Class.isAnnotationPresent
- Java SE 21 API — Class.getDeclaredAnnotationsByType
- Java SE 21 API — Class.getDeclaredAnnotation
- Java SE 21 API — AnnotatedElement: kinds of annotation presence
- Java SE 21 API — Inherited
- Java SE 21 API — RetentionPolicy.RUNTIME
- Java Language Specification, Java SE 21 — §9.6.3 Repeatable Annotation Interfaces
- Java Language Specification, Java SE 21 — §9.7.5 Multiple Annotations of the Same Interface
- Java Language Specification, Java SE 21 — §15.8.2 Class Literals