Close

Java Reflection - Class.getDeclaredAnnotationsByType() 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[] getDeclaredAnnotationsByType(Class<A> annotationClass)

The method returns this class's annotation(s) for the specified type if such annotations are either directly present or indirectly present.

Type Parameters:
A - the type of the annotation to query for and return if directly or indirectly present
Parameters:
annotationClass - the Class object corresponding to the annotation type
Returns:
all this element's annotations for the specified annotation type if directly or indirectly present on this element, else an array of length zero


Examples


package com.logicbig.example.clazz;

import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;

public class GetDeclaredAnnotationsByTypeExample {

public static void main(String... args) {
System.out.println("-- annotations by type--");
Deprecated[] d = MyClass.class.getAnnotationsByType(Deprecated.class);
System.out.println(Arrays.toString(d));

MyAnnotation[] m = MyClass.class.getAnnotationsByType(MyAnnotation.class);
System.out.println(Arrays.toString(m));
}

@Deprecated
public static class MyClass extends MySuperClass {
}

@MyAnnotation
public static class MySuperClass {
}

@Retention(RetentionPolicy.RUNTIME)
@Inherited
private static @interface MyAnnotation {
}
}

Output

-- annotations by type--
[@java.lang.Deprecated(forRemoval=false, since="")]
[@com.logicbig.example.clazz.GetDeclaredAnnotationsByTypeExample$MyAnnotation()]




See Also