封闭类与声明类
在任何情况下,Class.getDeclaringClass
可能会给出与 Class.getEnlookingClass
不同的结果吗?
我认为这可能与外部类的子类实例化未声明为静态的内部类有关,但我无法通过这种方式获得差异:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这里找到 http://kickjava.com/1139.htm#ixzz1mv2nEWg7:
“getDeclaringClass 的巧妙之处在 Java 语言规范中,匿名内部类不被视为类的成员,而命名内部类则被视为类的成员,因此此方法返回 null。对于匿名类,替代方法 getEnclosureClass 适用于匿名类和命名类。”
例如:
这同样适用于方法范围内的非匿名类:
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:
The same holds for non-anonymous classes in a method scope: