Javareflect-method-getannotation

提供:Dev Guides
移動先:案内検索

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)

パラメーター

*annotationClass* -注釈タイプに対応するClassオブジェクト。

返品

指定された注釈タイプに対するこの要素の注釈がこの要素に存在する場合は、そうでない場合はnull。

例外

*NullPointerException* -指定された注釈クラスがnullの場合。

次の例は、java.lang.reflect.Method.getAnnotation(Class <T> annotationClass)メソッドの使用方法を示しています。

package com.finddevguides;

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