📜  Java中的类 getDeclaredConstructor() 方法和示例

📅  最后修改于: 2022-05-13 01:54:42.056000             🧑  作者: Mango

Java中的类 getDeclaredConstructor() 方法和示例

Java.lang.Class类getDeclaredConstructor()方法用于获取该类指定参数类型的指定构造函数。该方法以Constructor对象的形式返回该类的指定构造函数。

句法:

public Constructor
       getDeclaredConstructor(Class[] parameterType)
       throws NoSuchMethodException, SecurityException

参数:此构造函数接受一个参数parameterType ,它是指定构造函数的参数类型数组。

返回值:该方法以Constructor对象的形式返回该类的指定构造函数。

异常此方法抛出:

  • 如果未找到具有指定名称的构造函数,则NoSuchMethodException
  • 如果存在安全管理器并且不满足安全条件,则出现 SecurityException。

    下面的程序演示了 getDeclaredConstructor() 方法。

    示例 1:

    // Java program to demonstrate
    // getDeclaredConstructor() method
      
    import java.util.*;
      
    public class Test {
      
        public Test() {}
      
        public static void main(String[] args)
            throws ClassNotFoundException, NoSuchMethodException
        {
      
            // returns the Class object for this class
            Class myClass = Class.forName("Test");
      
            System.out.println("Class represented by myClass: "
                               + myClass.toString());
      
            Class[] parameterType = null;
      
            // Get the constructor of myClass
            // using getDeclaredConstructor() method
            System.out.println(
                "Constructor of myClass: "
                + myClass.getDeclaredConstructor(parameterType));
        }
    }
    
    输出:
    Class represented by myClass: class Test
    Constructor of myClass: public Test()
    

    示例 2:

    // Java program to demonstrate
    // getDeclaredConstructor() constructor
      
    import java.util.*;
      
    class Main {
      
        private Main() {}
      
        public static void main(String[] args)
            throws ClassNotFoundException, NoSuchMethodException
        {
      
            // returns the Class object for this class
            Class myClass = Class.forName("Main");
      
            System.out.println("Class represented by myClass: "
                               + myClass.toString());
      
            Class[] parameterType = new Class[1];
            parameterType[0] = Long.class;
      
            try {
                // Get the constructor of myClass
                // using getDeclaredConstructor() method
                System.out.println(
                    "Constructor of myClass: "
                    + myClass.getDeclaredConstructor(parameterType));
            }
            catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    
    输出:
    Class represented by myClass: class Main
    java.lang.NoSuchMethodException: Main.(java.lang.Long)
    

    参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getDeclaredConstructor-java.lang.Class…-