私有内部类合成了意想不到的匿名类 [英] Private inner class synthesizes unexpected anonymous class
问题描述
当您使用私有内部类编译 Java 类时,似乎出于某种原因会自动合成一个匿名类.这个类足以重现它:
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 {}
}
编译时,这会生成预期的 SynthesizeAnonymous.class
和 SynthesizeAnonymous$InnerClass.class
文件,但也会生成一个奇怪的 SynthesizeAnonymous$1.class
code> 文件,对应于合成的 java.lang.Object
的匿名子类.如果你用javap
反汇编,看起来InnerClass
的默认构造函数获得了这个匿名类型的隐藏参数,而null
是当 new 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.
为什么要创建这个类?即使 InnerClass
不是静态的,它也会被创建,但如果 InnerClass
不是私有的或者没有 InnerClass
的实例,它也不会被创建创建.它是某种形式的访问控制吗?这是如何运作的?
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?
推荐答案
创建这个类是为了让您能够访问私有构造函数.
This class is created in order to provide you with access to private constructor.
看看这个问题了解详情.
这篇关于私有内部类合成了意想不到的匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!