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
Found here http://kickjava.com/1139.htm#ixzz1mv2nEWg7:
"The subtilty with getDeclaringClass is that anonymous inner classes are not counted as member of a class in the Java Language Specification whereas named inner classes are. Therefore this method returns null for an anonymous class. The alternative method getEnclosingClass works for both anonymous and named classes."
For example:
public class Test { public static void main(String[] args) { new Object() { public void test() { System.out.println(this.getClass().getDeclaringClass()); //null System.out.println(this.getClass().getEnclosingClass()); //not null } }.test(); } }
The same holds for non-anonymous classes in a method scope:
class Foo { Class<?> bar() throws NoSuchFieldException { class Bar<S> { } return Bar.class; } static void main(String[] args) throws NoSuchFieldException { System.out.println(new Foo<Void>().bar().getDeclaringClass()); // null System.out.println(new Foo<Void>().bar().getEnclosinglass()); // Foo } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With