Java中的类 getConstructors() 方法和示例
Java.lang.Class 类的getConstructors()方法用于获取该类的构造函数,也就是公共的构造函数。该方法以 Constructor 对象数组的形式返回该类的构造函数。
句法:
public Constructor[] getConstructors()
参数:此方法不接受任何参数。
返回值:该方法以Constructor对象数组的形式返回该类的构造函数。
异常如果存在安全管理器并且不满足安全条件,则此方法将引发SecurityException 。
下面的程序演示了 getConstructors() 方法。
示例 1:
Java
// Java program to demonstrate getConstructors() method
import java.util.*;
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// Get the constructors of myClass
// using getConstructors() method
System.out.println(
"Constructors of myClass: "
+ Arrays.toString(
myClass.getConstructors()));
}
}
Java
// Java program to demonstrate getConstructors() method
import java.util.*;
class Main {
public Object obj;
private Main()
{
class Arr {
};
obj = new Arr();
}
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Main");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// Get the constructors of myClass
// using getConstructors() method
System.out.println(
"Constructors of myClass: "
+ Arrays.toString(
myClass.getConstructors()));
}
}
输出:
Class represented by myClass: class Test
Constructors of myClass: [public Test()]
示例 2:
Java
// Java program to demonstrate getConstructors() method
import java.util.*;
class Main {
public Object obj;
private Main()
{
class Arr {
};
obj = new Arr();
}
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Main");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// Get the constructors of myClass
// using getConstructors() method
System.out.println(
"Constructors of myClass: "
+ Arrays.toString(
myClass.getConstructors()));
}
}
输出:
Class represented by myClass: class Main
Constructors of myClass: []
参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getConstructors–