Close

Java Reflection - Field.getAnnotations() 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 Annotation[] getAnnotations()

Returns annotations that are present on this element. If there are no annotations present on this element, the return value is an array of length 0.


Examples


package com.logicbig.example.field;

import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.Arrays;

public class GetAnnotationsExample {

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

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

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

}

Output

2
@java.lang.Deprecated(forRemoval=false, since="")
@com.logicbig.example.field.GetAnnotationsExample$ReadOnly()




See Also