Are there any circumstances in which Class.getDeclaringClass
could give a different result from Class.getEnclosingClass
?
I thought it may be to do with a subclass of the outer class instantiating an inner class that was not declared as static, but I wasn't able to get a difference that way:
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() );
}
}
Output:
class Main
class Main
class Main
class Main
class Main
class Main
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…