Close

Java Reflection - Class.getAnnotationsByType() Examples

Code Snippets Java Reflection Java Java API 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass)

This method returns annotations that are associated with this element. If there are no annotations associated with this element, the return value is an array of length 0. The difference between this method and AnnotatedElement.getAnnotation(Class) is that this method detects if its argument is a repeatable annotation type, and if so, attempts to find one or more annotations of that type by "looking through" a container annotation.


Examples


package com.logicbig.example.clazz;

import java.util.Arrays;

public class GetAnnotationsByTypeExample {

public static void main(String... args) {
Deprecated[] annotationsByType = MyClass.class
.getAnnotationsByType(Deprecated.class);
System.out.println(Arrays.asList(annotationsByType));
}

@Deprecated
private static class MyClass {
}
}

Output

[@java.lang.Deprecated()]




package com.logicbig.example.clazz;

import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class GetAnnotationsByTypeExample2 {

public static void main(String... args) {
System.out.println("-- using getAnnotation(MultiAccess.class) --");
MultiAccess multiAccess = MyClass.class
.getAnnotation(MultiAccess.class);
for (Access access : multiAccess.value()) {
System.out.println(access);
}

System.out.println("-- using getAnnotationsByType(Access.class) --");
Access[] accessAnnotations = MyClass.class
.getAnnotationsByType(Access.class);
for (Access access : accessAnnotations) {
System.out.println(access);
}
}

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MultiAccess.class)
public @interface Access {
String value() default "ADMIN";
}

@Retention(RetentionPolicy.RUNTIME)
public @interface MultiAccess {
Access[] value() default @Access;
}

@MultiAccess({@Access("SUPER_USER"), @Access("CUSTOMER")})
private static class MyClass {
}
}

Output

-- using getAnnotation(MultiAccess.class) --
@com.logicbig.example.clazz.GetAnnotationsByTypeExample2$Access(value=SUPER_USER)
@com.logicbig.example.clazz.GetAnnotationsByTypeExample2$Access(value=CUSTOMER)
-- using getAnnotationsByType(Access.class) --
@com.logicbig.example.clazz.GetAnnotationsByTypeExample2$Access(value=SUPER_USER)
@com.logicbig.example.clazz.GetAnnotationsByTypeExample2$Access(value=CUSTOMER)




See Also