The java.lang.reflect.Method.getAnnotation(Class< T > annotationClass) method of Method class returns Method objects’s annotation for the specified type passed as parameter if such an annotation is present, else null. This is important method to get annotation for Method object.
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
Parameter: This method takes a mandatory parameter annotationClass which is the Class object of the annotation type.
Return Value: This method returns the method’s annotation for the specified annotation type if present on this element, else null.
Exception: This method throws NullPointerException if the given annotation class is null
Below program illustrates getAnnotation(Class annotationClass) method of Method class:
Example 1: This program prints method’s annotation for the specified annotation type given as parameter to getAnnotation() of Method Object representing getCustomAnnotation() method of GFG class.
In thi,s example a single class is used and class contains both methods which are main method and method with annotation.
Annotation for Method Object having name: getCustomAnnotation Key Attribute of Annotation: AvengersLeader Value Attribute of Annotation: CaptainAmerica
Example 2: This program prints method’s annotation for the specified annotation type given as parameter to getAnnotation() of Method Object representing getCustomAnnotation() method of GFG class.
In this example a two classes is used.One class contains main method which creates the method object and applying getAnnotation() method and other class contains method with some annotation.
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.