turn:
java.lang.reflect.Method.getAnnotation () method of Example
java.lang.reflect.Method.getAnnotation(Class <T> annotationClass)
If such a method exists comment, annotation elements of the specified type is returned, otherwise null
.
statement
The following is a java.lang.reflect.Method.getAnnotation(Class <T> annotationClass)
statement of the method.
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
parameter
- annotationClass -
Class
object type of the corresponding comment.
return value
- If there is this element, the element annotation annotation type specified is returned, otherwise returns
null
.
abnormal
- NullPointerException - if the given annotation class is empty.
The following example shows java.lang.reflect.Method.getAnnotation(Class<T> annotationClass)
the use of the method.
package sync; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; public class MethodDemo { public static void main(String[] args) { Method[] methods = SampleClass.class.getMethods(); Annotation annotation = methods[0].getAnnotation(CustomAnnotation.class); if(annotation instanceof CustomAnnotation){ CustomAnnotation customAnnotation = (CustomAnnotation) annotation; System.out.println("name: " + customAnnotation.name()); System.out.println("value: " + customAnnotation.value()); } } } @CustomAnnotation(name="SampleClass", value = "Sample Class Annotation") class SampleClass { private String sampleField; @CustomAnnotation(name="getSampleMethod", value = "Sample Method Annotation") public String getSampleField() { return sampleField; } public void setSampleField(String sampleField) { this.sampleField = sampleField; } } @Retention(RetentionPolicy.RUNTIME) @interface CustomAnnotation { public String name(); public String value(); }
Let's compile and run the above program, which will produce the following results -
name: getSampleMethod
value: Sample Method Annotation
From the original tutorial] [EBEY, commercial reprint please contact the author authorized, non-commercial reprint please retain the original link: https: //www.yiibai.com/javareflect/javareflect_method_getannotation.html