Java中的类 getEnclosureConstructor() 方法和示例
Java.lang.Class 类的getEnclosureConstructor()方法用于获取该类的封闭构造函数。如果此类是在该构造函数中声明的本地类或匿名类,则该方法返回此类的封闭构造函数。否则此方法返回 null。
句法:
public Constructor getEnclosingConstructor()
参数:此方法不接受任何参数。
返回值:如果此类是在该构造函数中声明的本地类或匿名类,则此方法返回该类的封闭构造函数。否则,此构造函数返回 null。
异常如果存在安全管理器并且不满足安全条件,则此方法将引发SecurityException 。
下面的程序演示了 getEnclosureConstructor() 方法。
示例 1:
Java
// Java program to demonstrate
// getEnclosingConstructor() 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 enclosing constructors of myClass
// using getEnclosingConstructor() constructor
System.out.println("EnclosingConstructor of myClass: "
+ myClass.getEnclosingConstructor());
}
}
Java
// Java program to demonstrate
// getEnclosingConstructor() method
import java.util.*;
class Main {
public Object obj;
Main()
{
class Arr {
};
obj = new Arr();
}
public static void main(String[] args)
throws ClassNotFoundException
{
Main t = new Main();
// returns the Class object
Class myClass = t.obj.getClass();
// Get the enclosing constructors of myClass
// using getEnclosingConstructor() constructor
System.out.println("EnclosingConstructor of myClass: "
+ myClass.getEnclosingConstructor());
}
}
输出:
Class represented by myClass: class Test
EnclosingConstructor of myClass: null
示例 2:
Java
// Java program to demonstrate
// getEnclosingConstructor() method
import java.util.*;
class Main {
public Object obj;
Main()
{
class Arr {
};
obj = new Arr();
}
public static void main(String[] args)
throws ClassNotFoundException
{
Main t = new Main();
// returns the Class object
Class myClass = t.obj.getClass();
// Get the enclosing constructors of myClass
// using getEnclosingConstructor() constructor
System.out.println("EnclosingConstructor of myClass: "
+ myClass.getEnclosingConstructor());
}
}
输出:
EnclosingConstructor of myClass: Main()
参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getEnclosureConstructor–