Close

Java Reflection - Field.getDeclaredAnnotationsByType() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Field

java.lang.Objectjava.lang.Objectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AnnotatedElementAnnotatedElementjava.lang.reflect.Fieldjava.lang.reflect.Fieldjava.lang.reflect.MemberMemberLogicBig

Method:

public <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass)

Returns this element's annotation(s) for the specified type if such annotations are either directly present or indirectly present.


Examples


package com.logicbig.example.field;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.Arrays;

public class GetDeclaredAnnotationsByTypeExample {

private static class Test {
@Deprecated
@ReadOnly
private String str;
}


public static void main(String... args) throws NoSuchFieldException {
Field f = Test.class.getDeclaredField("str");
ReadOnly[] a = f.getDeclaredAnnotationsByType(ReadOnly.class);
System.out.println(a.length);
Arrays.stream(a).forEach(System.out::println);
}

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
private @interface ReadOnly {}

}

Output

1
@com.logicbig.example.field.GetDeclaredAnnotationsByTypeExample$ReadOnly()




See Also