转:
java.lang.reflect.Method.getAnnotation()方法示例
java.lang.reflect.Method.getAnnotation(Class <T> annotationClass)方法如果存在这样的注释,则返回指定类型的元素的注释,否则为null。
声明
以下是java.lang.reflect.Method.getAnnotation(Class <T> annotationClass)方法的声明。
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
Java
参数
- annotationClass -
Class对象对相应的注释类型。
返回值
- 如果存在于此元素,则返回该元素注释指定的注释类型,否则返回为
null。
异常
- NullPointerException - 如果给定的注释类为空。
以下示例显示java.lang.reflect.Method.getAnnotation(Class<T> annotationClass)方法的用法。
1package sync; 2import java.lang.annotation.Annotation; 3import java.lang.annotation.Retention; 4import java.lang.annotation.RetentionPolicy; 5import java.lang.reflect.Method; 6 7public class MethodDemo { 8 public static void main(String[] args) { 9 Method[] methods = SampleClass.class.getMethods(); 10 11 Annotation annotation = methods[0].getAnnotation(CustomAnnotation.class); 12 if(annotation instanceof CustomAnnotation){ 13 CustomAnnotation customAnnotation = (CustomAnnotation) annotation; 14 System.out.println("name: " + customAnnotation.name()); 15 System.out.println("value: " + customAnnotation.value()); 16 } 17 } 18} 19 20@CustomAnnotation(name="SampleClass", value = "Sample Class Annotation") 21class SampleClass { 22 private String sampleField; 23 24 @CustomAnnotation(name="getSampleMethod", value = "Sample Method Annotation") 25 public String getSampleField() { 26 return sampleField; 27 } 28 29 public void setSampleField(String sampleField) { 30 this.sampleField = sampleField; 31 } 32} 33 34@Retention(RetentionPolicy.RUNTIME) 35@interface CustomAnnotation { 36 public String name(); 37 public String value(); 38}
Java
让我们编译并运行上面的程序,这将产生以下结果 -
1name: getSampleMethod 2value: Sample Method Annotation
Shell
原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/javareflect/javareflect\_method\_getannotation.html