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

    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
    
    原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/javareflect/javareflect_method_getannotation.html

  • 相关阅读:
    mysql5.7.22安装步骤
    idea 配置http代理
    大话设计模式之类与类之间的关系读后感
    大话设计模式之工厂方法模式读后感
    rabbitmq+java入门(五)Topic
    rabbitmq+java入门(四)routing
    rabbitmq+java入门(二) 工作队列
    rabbitmq+java入门(三)exchange的使用
    rabbitmq+java入门(一)hello world
    idea+jrebel+springboot热部署
  • 原文地址:https://www.cnblogs.com/libin6505/p/11212171.html
Copyright © 2020-2023  润新知