私有内部类综合了意想不到的匿名类
当您编译带有私有内部类的 Java 类时,由于某种原因,似乎会自动合成一个匿名类。 这个类足以重现它:
public class SynthesizeAnonymous {
public static void method() {
new InnerClass();
}
private static class InnerClass {}
}
编译时,会生成预期的 SynthesizeAnonymous.class
和 SynthesizeAnonymous$InnerClass.class
文件,但它也会生成一个奇怪的 SynthesizeAnonymous $1.class
文件,对应于合成的 java.lang.Object
的匿名子类。 如果您使用 javap
查看反汇编,就会发现 InnerClass
的默认构造函数获得了此匿名类型的隐藏参数,并且 null
是当调用 new InnerClass()
时传递给它。
为什么要创建这个类? 即使 InnerClass
不是静态的,它也会被创建,但如果 InnerClass
不是私有的或者没有 InnerClass
的实例,它就不会被创建创建的。 它是某种形式的访问控制吗? 这是如何运作的?
When you compile a Java class with a private inner class, it appears that an anonymous class is automatically synthesized along with it for some reason. This class is sufficient to reproduce it:
public class SynthesizeAnonymous {
public static void method() {
new InnerClass();
}
private static class InnerClass {}
}
When compiled, this generates the expected SynthesizeAnonymous.class
and SynthesizeAnonymous$InnerClass.class
files, but it also generates a strange SynthesizeAnonymous$1.class
file that corresponds to an anonymous subclass of java.lang.Object
that was synthesized. If you look at the disassembly with javap
, it appears the default constructor of InnerClass
gains a hidden parameter of this anonymous type, and that null
is passed to it when the new InnerClass()
is called.
Why is this class created? It's created even if InnerClass
isn't static, but it isn't created if InnerClass
isn't private or no instance of InnerClass
is ever created. Is it some form of access control? How does that work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建此类是为了向您提供对私有构造函数的访问。
看看这个问题 详细信息。
This class is created in order to provide you with access to private constructor.
Take a look at this question for details.