Javareflect-field-getannotation
提供:Dev Guides
java.lang.reflect.Field.getAnnotation()メソッドの例
説明
- java.lang.reflect.Field.getAnnotation(Class <T> annotationClass)*メソッドは、そのような注釈が存在する場合は指定されたタイプのこの要素の注釈を返し、そうでない場合はnullを返します。
宣言
以下は、* java.lang.reflect.Field.getAnnotation(Class <T> annotationClass)*メソッドの宣言です。
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
パラメーター
*annotationClass* -注釈タイプに対応するClassオブジェクト。
返品
指定された注釈タイプに対するこの要素の注釈がこの要素に存在する場合は、そうでない場合はnull。
例外
*NullPointerException* -指定された注釈クラスがnullの場合。
例
次の例は、java.lang.reflect.Field.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.Field;
public class FieldDemo {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Field field = SampleClass.class.getField("sampleField");
Annotation annotation = field.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 {
@CustomAnnotation(name="sampleClassField", value = "Sample Field Annotation")
public String sampleField;
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: sampleClassField
value: Sample Field Annotation