Java Method getAnnotation()方法

java.lang.reflect.Method.getAnnotation(Class <T> annotationClass)方法如果存在这样的注释,则返回指定类型的元素的注释,否则为null。

1 语法

public <T extends Annotation> T getAnnotation(Class<T> annotationClass)

2 参数

annotationClass : Class对象对相应的注释类型。

3 返回值

如果存在于此元素,则返回该元素注释指定的注释类型,否则返回为null。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Method getAnnotation()方法
 */
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();
}

输出结果为:

name: getSampleMethod
value: Sample Method Annotation

 

热门文章

优秀文章