zoukankan      html  css  js  c++  java
  • java.lang.reflect.Method.getAnnotation()方法示例【通过反射获取到方法对象再获取方法对象上的注解信息】

    转:

    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)方法的用法。

    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();
    }
    Java

    让我们编译并运行上面的程序,这将产生以下结果 -

    name: getSampleMethod
    value: Sample Method Annotation
    
    Shell
    原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/javareflect/javareflect_method_getannotation.html

  • 相关阅读:
    自动化单元测试
    Exadata是什么?
    Exadata的独门武器卸载(Offloading)
    Exadata中最有用的功能存储索引
    面向对象分析与设计(第3版)
    代码质量(权威精选植根于开发实践的最佳读物)
    温昱谈程序员向架构师转型的规律
    sql语句大全
    一个弹出层的代码
    ASP.NET 2.0 实现伪静态网页方法 (转载 ————续)
  • 原文地址:https://www.cnblogs.com/libin6505/p/11227149.html
Copyright © 2011-2022 走看看