封闭类与声明类
2022-09-01 23:08:48
是否有任何情况可能会产生与 ?Class.getDeclaringClass
Class.getEnclosingClass
我认为这可能与外部类的子类实例化未声明为静态的内部类有关,但我无法以这种方式获得差异:
public class Main {
private static class StaticInnerClass {
}
private class MemberInnerClass {
}
private static class ChildClass extends Main {
}
public MemberInnerClass getMemberInnerClassInstance() {
return new MemberInnerClass();
}
public static void main(String[] args) {
System.out.println( StaticInnerClass.class.getDeclaringClass() );
System.out.println( StaticInnerClass.class.getEnclosingClass() );
System.out.println( MemberInnerClass.class.getDeclaringClass() );
System.out.println( MemberInnerClass.class.getEnclosingClass() );
System.out.println( new ChildClass().getMemberInnerClassInstance().getClass().getEnclosingClass() );
System.out.println( new ChildClass().getMemberInnerClassInstance().getClass().getDeclaringClass() );
}
}
输出:
class Main
class Main
class Main
class Main
class Main
class Main