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 − 對應於註釋型別的類物件。

返回值

如果此元素存在指定註釋型別,則返回此元素的該註釋,否則返回 null。

異常

空指標異常 − 如果給定的註釋類為 null。

示例

以下示例演示了 java.lang.reflect.Field.getAnnotation(Class<T> annotationClass) 方法的用法。

package com.tutorialspoint;

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
java_reflect_field.htm
廣告
© . All rights reserved.