Java Constructor getDeclaredAnnotations()方法及示例
java.lang.reflect.Constructor类 的 getDeclaredAnnotations() 方法用于返回存在于该Constructor元素上的注释,作为一个注释类对象的数组。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()
