私有内部类综合了意想不到的匿名类

发布于 2024-08-01 21:10:09 字数 759 浏览 5 评论 0原文

当您编译带有私有​​内部类的 Java 类时,由于某种原因,似乎会自动合成一个匿名类。 这个类足以重现它:

public class SynthesizeAnonymous {
    public static void method() {
        new InnerClass();
    }

    private static class InnerClass {}
}

编译时,会生成预期的 SynthesizeAnonymous.classSynthesizeAnonymous$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

世俗缘 2024-08-08 21:10:09

创建此类是为了向您提供对私有构造函数的访问。

看看这个问题 详细信息。

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

Take a look at this question for details.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文