Java 中的类 getDeclaredConstructors()方法,带示例
原文:https://www . geesforgeks . org/class-getdeclaredconstructors-method-in-Java-with-examples/
java.lang.Class 类 的getDeclaredConstructors()方法用于获取该类的构造函数,这些构造函数是私有的、公共的、受保护的或默认的。方法以构造函数对象数组的形式返回该类的构造函数。 语法:
public Constructor[] getDeclaredConstructors()
throws SecurityException
参数:此方法不接受任何参数。 返回值:这个方法以 Constructor 对象数组的形式返回这个类的构造函数。 异常如果有安全管理人员在场且不满足安全条件,此方法抛出安全异常。 下面的程序演示了 getDeclaredConstructors()方法。 例 1:
Java 语言(一种计算机语言,尤用于创建网站)
// Java program to demonstrate
// getDeclaredConstructors() 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 getDeclaredConstructors() method
System.out.println(
"DeclaredConstructors of myClass: "
+ Arrays.toString(
myClass.getDeclaredConstructors()));
}
}
Output:
Class represented by myClass: class Test
DeclaredConstructors of myClass: [public Test()]
例 2:
Java 语言(一种计算机语言,尤用于创建网站)
// Java program to demonstrate
//getDeclaredConstructors() 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 getDeclaredConstructors() method
System.out.println(
"DeclaredConstructors of myClass: "
+ Arrays.toString(
myClass.getDeclaredConstructors()));
}
}
Output:
Class represented by myClass: class Main
DeclaredConstructors of myClass: [private Main()]
参考:T2【https://docs . Oracle . com/javase/9/docs/API/Java/lang/class . html # getDeclaredConstructors–T4】
版权属于:月萌API www.moonapi.com,转载请注明出处