The java.lang.reflect.Method.getDeclaredAnnotations() method of Method class returns annotations declared only on the method and ignores inherited annotations by method. If there are no annotations directly declared on the method, the returned array of annotation is empty. Modification of the returned array will have no effect on the arrays returned to other callers. All returned array of annotations are independent to each other when they called by the different caller.
public Annotation getDeclaredAnnotations()
Return Value: This method returns an array of annotations directly present on this element
Below program illustrates getDeclaredAnnotations() method of Method class:
Program 1: This Program prints annotations declared only on the method and ignores inherited annotations by method using getDeclaredAnnotations() method on Method object.
Annotation details key: AvengersLeader value: CaptainAmerica
Program 2: This Program prints annotations declared only on the method and ignores inherited annotations by method using getDeclaredAnnotations() method on Method object of other class.
In this program there are two different classes. One class contains method with some annotation and other class contains main method. In main Method method object for the method of other class containing annotation is created. After creating method object using getDeclaredAnnotations() method annotations declared only on the method is collected and after collecting annotation Info program is printing the result.
key: getField value: getting field attribute
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.