当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Class getDeclaredConstructor()用法及代码示例


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

用法:

public Constructor<T>
       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…-



相关用法


注:本文由纯净天空筛选整理自srinam大神的英文原创作品 Class getDeclaredConstructor() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。