类的类getDeclaredConstructor()方法 (Class class getDeclaredConstructor() method)
getDeclaredConstructor() method is available in java.lang package.
getDeclaredConstructor()方法在java.lang包中可用。
getDeclaredConstructor() method is used to return a Constructor object that indicates the given constructor of the class denoted by this Class object.
getDeclaredConstructor()方法用于返回一个Constructor对象,该对象指示由此Class对象表示的类的给定构造函数。
getDeclaredConstructor() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
getDeclaredConstructor()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名访问该方法,则会收到错误消息。
getDeclaredConstructor() method may throw an exception at the time of returning a Constructor object.
getDeclaredConstructor()方法可能会在返回Constructor对象时引发异常。
- NoSuchMethodException: In this exception when a specifying method does not exist.NoSuchMethodException :在此异常中,当指定方法不存在时。
- SecurityException: In this exception, it may raise when the security manager exists.SecurityException :在此异常中,当安全管理器存在时可能会引发此异常。
Syntax:
句法:
public Constructor getDeclaredConstructor (Class ...paramType);
Parameter(s):
参数:
Class ...paramType – represents the parameter array.
Class ... paramType –表示参数数组。
Return value:
返回值:
The return type of this method is Constructor, it returns Constructor object for the constructor with the given set of paramType.
此方法的返回类型为Constructor ,它使用给定的paramType集返回构造函数的Constructor对象。
Example:
例:
// Java program to demonstrate the example
// of Constructor getDeclaredConstructor (Class ...paramType) method of Class
import java.lang.reflect.*;
public class GetDeclaredConstructorOfClass {
public static void main(String[] args) throws Exception {
GetDeclaredConstructorOfClass dc = new GetDeclaredConstructorOfClass();
Class cl = dc.getClass();
Class[] cons_argument = new Class[3];
cons_argument[0] = Integer.class;
cons_argument[1] = Short.class;
cons_argument[2] = Long.class;
Constructor cons = cl.getDeclaredConstructor(cons_argument);
System.out.println("Declared Constructor:" + cons.toString());
}
protected GetDeclaredConstructorOfClass(Integer i, Short s, Long l) {
this.i = i;
this.s = s;
this.l = l;
}
public GetDeclaredConstructorOfClass() {
System.out.println("We are in public Constructor");
}
short sh = 10;
Integer i = new Integer(100);
Short s = new Short(sh);
Long l = new Long(30l);
}
Output
输出量
We are in public Constructor
Declared Constructor:protected GetDeclaredConstructorOfClass(java.lang.Integer,java.lang.Short,java.lang.Long)
翻译自: https://www.includehelp.com/java/class-class-getdeclaredconstructor-method-with-example.aspx