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


Java Constructor getDeclaredAnnotations()用法及代碼示例


java.lang.reflect.Constructor類的getDeclaredAnnotations()方法用於返回存在於此Constructor元素上的注釋,作為Annotation類對象的數組。 getDeclaredAnnotations()方法將忽略此構造方法對象上的繼承注釋。返回的數組不能包含任何注釋,如果構造函數具有nop注釋,則該數組的長度可以為0。

用法:

public Annotation[] getDeclaredAnnotations()

參數:此方法不接受任何內容。


返回:此方法返回直接存在於此元素上的注釋數組

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

// Java program to illustrate 
// getDeclaredAnnotations() method 
  
import java.lang.annotation.Annotation; 
import java.lang.reflect.Constructor; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
        // create a class object 
        Class classObj = shape.class; 
  
        // get Constructor object 
        // array from class object 
        Constructor[] cons 
            = classObj.getConstructors(); 
  
        // get array of annotations 
        Annotation[] annotations 
            = cons[0].getDeclaredAnnotations(); 
  
        // print length of annotations array 
        System.out.println("Annotation : "
                           + annotations); 
    } 
  
    @CustomAnnotation(createValues = "GFG") 
    public class shape { 
  
        @CustomAnnotation(createValues = "GFG") 
        public shape() 
        { 
        } 
    } 
  
    // create a custom annotation 
    public @interface CustomAnnotation { 
        public String createValues(); 
    } 
    }
輸出:
Annotation : [Ljava.lang.annotation.Annotation;@4aa298b7

示例2:

// Java program to illustrate 
// getDeclaredAnnotations() method 
  
import java.lang.annotation.Annotation; 
import java.lang.reflect.Constructor; 
  
public class GFG { 
  
    public static void main(String[] args) 
    { 
        // create a class object 
        Class classObj = String.class; 
  
        // get Constructor object 
        // array from class object 
        Constructor[] cons 
            = classObj.getConstructors(); 
  
        // get array of annotations 
        Annotation[] annotations 
            = cons[0].getDeclaredAnnotations(); 
  
        // print length of annotations array 
        System.out.println("Annotation length : "
                           + annotations.length); 
    } 
}
輸出:
Annotation length : 0

參考文獻: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getDeclaredAnnotations()



相關用法


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