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

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

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

Java.lang.Class类getConstructor()方法用于获取该类指定参数类型的构造函数,该构造函数是public及其成员。该方法以Constructor对象的形式返回该类的指定构造函数。

句法:

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

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

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

异常此方法抛出:

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

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

    示例 1:

    // Java program to demonstrate
    // getConstructor() 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 getConstructor() method
            System.out.println(
                "Constructor of myClass: "
                + myClass.getConstructor(parameterType));
        }
    }
    
    输出:
    Class represented by myClass: class Test
    Constructor of myClass: public Test()
    

    示例 2:

    // Java program to demonstrate
    // getConstructor() 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 = null;
      
            try {
                // Get the constructor of myClass
                // using getConstructor() method
                System.out.println(
                    "Constructor of myClass: "
                    + myClass.getConstructor(parameterType));
            }
            catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    
    输出:
    Class represented by myClass: class Main
    java.lang.NoSuchMethodException: Main.()
    

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