Java Class getConstructor() 方法



描述

Java Class getConstructor() 方法返回一個 Constructor 物件,該物件反映由此 Class 物件表示的類的指定公共建構函式。parameterTypes 引數是一個 Class 物件陣列,按宣告順序標識建構函式的形式引數型別。

宣告

以下是 java.lang.Class.getConstructor() 方法的宣告

public Constructor<T> getConstructor(Class<?>... parameterTypes)
   throws NoSuchMethodException, SecurityException

引數

parameterTypes - 這是引數陣列。

返回值

此方法返回與指定 parameterTypes 匹配的公共建構函式的 Constructor 物件。

異常

  • NoSuchMethodException - 如果找不到匹配的方法。

  • SecurityException - 如果存在安全管理器 s。

獲取 String 類建構函式示例

以下示例演示了 java.lang.Class.getConstructor() 方法的用法。在這個程式中,我們建立了一個 Class 陣列的例項,然後用 String 類初始化它。現在使用 getConstructor() 方法,檢索例項的建構函式,並列印結果。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      try {
         // returns the Constructor object of the public constructor
         Class cls[] = new Class[] { String.class };
         Constructor c = String.class.getConstructor(cls);
         System.out.println(c);
      } catch(Exception e) {
         System.out.println(e);
      } 
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

public java.lang.String(java.lang.String)

獲取自定義類建構函式示例

以下示例演示了 java.lang.Class.getConstructor() 方法的用法。在這個程式中,我們建立了一個 Class 陣列的例項,然後用 ClassDemo 類初始化它。現在使用 getConstructor() 方法,檢索例項的建構函式,並列印結果。

package com.tutorialspoint;

import java.lang.reflect.Constructor;

public class ClassDemo {

   public ClassDemo(ClassDemo demo){
      // constructor
   }

   public static void main(String[] args) {
	   
	  ClassDemo classDemo = new ClassDemo(null);
	  
	  Class clazz = classDemo.getClass();
      try {
         // returns the Constructor object of the public constructor
         Class cls[] = new Class[] { clazz };
         Constructor c = clazz.getConstructor(cls);
         System.out.println(c);
      } catch(Exception e) {
         System.out.println(e);
      } 
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

public com.tutorialspoint.ClassDemo(com.tutorialspoint.ClassDemo)

獲取 List 類建構函式示例

以下示例演示了 java.lang.Class.getConstructor() 方法的用法。在這個程式中,我們建立了一個 Class 陣列的例項,然後用 List 類初始化它。現在使用 getConstructor() 方法,檢索例項的建構函式,並列印結果。

package com.tutorialspoint;

import java.lang.reflect.Constructor;
import java.util.List;

public class ClassDemo {

   public static void main(String[] args) {

      try {
         // returns the Constructor object of the public constructor
         Class cls[] = new Class[] { };
         Constructor c = List.class.getConstructor(cls);
         System.out.println(c);
      } catch(Exception e) {
         System.out.println(e);
      } 
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

java.lang.NoSuchMethodException: java.util.List.<init>()
java_lang_class.htm
廣告

© . All rights reserved.