當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。