Private inner class synthesizes unexpected anonymous class

前提是你 提交于 2019-12-06 01:58:06

问题


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?


回答1:


This class is created in order to provide you with access to private constructor.

Take a look at this question for details.



来源:https://stackoverflow.com/questions/1267537/private-inner-class-synthesizes-unexpected-anonymous-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!