當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Field getAnnotation()用法及代碼示例


如果存在這樣的注釋,則使用java.lang.reflect.Field的getAnnotation()方法來返回指定類型的Field對象的返回值,否則返回null。這是獲取Field對象注釋的重要方法。

用法:

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

參數:此方法注釋類是與注釋類型相對應的Class對象。


返回:如果此元素上存在指定的注釋類型,則此方法返回該元素的注釋,否則返回null。

異常注意:如果給定的注釋類為null,則此方法將引發NullPointerException。

以下示例程序旨在說明getAnnotation()方法:
示例1:

// Java program to illustrate 
// getAnnotation() method 
  
import java.lang.annotation.*; 
import java.lang.reflect.AnnotatedType; 
import java.lang.reflect.Field; 
import java.util.Arrays; 
  
public class GFG { 
  
    // initialize field with 
    // default value in annotation 
    @annotations(3125462345.32155365326) 
  
    private double realNumbers; 
  
    public static void main(String[] args) 
        throws NoSuchFieldException 
    { 
  
        // create Field object 
        Field field 
            = GFG.class
                  .getDeclaredField("realNumbers"); 
  
        // apply getAnnotation() 
        annotations annotations 
            = field.getAnnotation( 
                annotations.class); 
  
        // print results 
        System.out.println(annotations); 
    } 
  
    @Target({ ElementType.FIELD }) 
    @Retention(RetentionPolicy.RUNTIME) 
    private @interface annotations { 
        double value() default 99.9; 
    } 
}
輸出:
@GFG$annotations(value=3.1254623453215537E9)

示例2:

// Java program to illustrate 
// getAnnotation() method 
  
import java.lang.annotation.*; 
import java.lang.reflect.AnnotatedType; 
import java.lang.reflect.Field; 
import java.util.Arrays; 
  
public class GFG { 
    private int @SpecialNumber[] number; 
  
    public static void main(String[] args) 
        throws NoSuchFieldException 
    { 
        // get Field object 
        Field field 
            = GFG.class
                  .getDeclaredField("number"); 
  
        // apply getAnnotation() method 
        AnnotatedType annotatedType 
            = field.getAnnotation(); 
  
        // print the results 
        System.out.println( 
            "Type: "
            + annotatedType.getType() 
                  .getTypeName()); 
        System.out.println( 
            "Annotations: "
            + Arrays.toString( 
                  annotatedType 
                      .getAnnotations())); 
        System.out.println( 
            "Declared Annotations: "
            + Arrays.toString( 
                  annotatedType 
                      .getDeclaredAnnotations())); 
    } 
  
    @Target({ ElementType.TYPE_USE }) 
    @Retention(RetentionPolicy.RUNTIME) 
    private @interface SpecialNumber { 
    } 
}
輸出:
@GFG$annotations(value=WelcomeTOGFG)

參考文獻: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getAnnotation–



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Field getAnnotation() method in Java With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。