Java Constructor getParameterAnnotations()方法及示例

来源:这里教程网 时间:2026-02-17 20:44:11 作者:

Java Constructor getParameterAnnotations()方法及示例

构造函数 类的 getParameterAnnotations() 方法用于获取一个二维的注释数组,代表该构造函数的正式参数的注释。如果构造函数不包含参数,将返回一个空数组。如果构造函数包含一个或多个参数,那么将返回一个二维注解数组。对于没有注释的参数,这个二维数组的嵌套数组将是空的。该方法返回的注释对象是可序列化的。由该方法返回的数组可以很容易地被修改。

语法

public Annotation[][] getParameterAnnotations()

参数: 该方法不接受任何东西。

返回值: 该方法返回一个 数组 ,代表该对象所代表的可执行文件的正式参数和隐式参数的注释,按声明顺序排列。

下面的程序说明了getParameterAnnotations()方法:

程序1 :

// Java program to demonstrate// Constructor.getParameterAnnotations() method  import java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Constructor;import java.util.Arrays;  public class GFG {      public static void main(String... args)        throws NoSuchMethodException    {          // Create Constructor Object        Constructor[] constructors            = Test.class.getConstructors();          // get Annotation array        Annotation[][] annotations            = constructors[0].getParameterAnnotations();          System.out.println("Parameter annotations -->");        System.out.println(Arrays.deepToString(annotations));    }}class Test {      public Test(@Properties Object config)    {    }}  @Retention(RetentionPolicy.RUNTIME)@interface Properties {}

输出。

Parameter annotations -->[[@Properties()]]

程序2

// Java program to demonstrate// Constructor.getParameterAnnotations() method  import java.lang.annotation.Annotation;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Constructor;  public class GFG {      public static void main(String... args)        throws NoSuchMethodException    {          // Create Constructor Object        Constructor[] constructors            = GfgDemo.class.getConstructors();          // get Annotation array        Annotation[][] annotations            = constructors[0].getParameterAnnotations();          System.out.println("Parameter annotations -->");        for (Annotation[] ann : annotations) {            for (Annotation annotation : ann) {                System.out.println(annotation);            }        }    }}class GfgDemo {      public GfgDemo(@Path Path path)    {    }}  @Retention(RetentionPolicy.RUNTIME)@interface Path {}

输出。

Parameter annotations -->@Path()

参考文献: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getParameterAnnotations()

相关推荐