Are there any circumstances in which Class.getDeclaringClass
could give a different result from Class.getEnclosingClass
?
I thought it may b
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
}
}