java 为什么在这种情况下会生成 classname$1.class?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17006585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:40:56  来源:igfitidea点击:

Why does classname$1.class generate in this situation?

javacompilation

提问by handrenliang

I wrote the following code to implement the Singleton pattern:

我编写了以下代码来实现单例模式:

public final class Test {
     static final class TestHolder {
         private static final Test INSTANCE = new Test();
     }     

     private Test() {}

     public static Test getInstance() {
         return TestHolder.INSTANCE;
     }
}

When I compile this file, it should generate Test.class and Test$TestHolder.class, but it also generates Test$1.class. This doesn't make sense. So why and how would this be?

当我编译这个文件时,它应该生成Test.class 和Test$TestHolder.class,但它也会生成Test$1.class。这没有意义。那么为什么会这样?

回答by Ernest Friedman-Hill

Class TestHolderneeds to call the private constructor in Test. But it's private, and can't actually be called from another class. So the compiler plays a trick. It adds a new non-private constructor to Testwhich only it knows about!That constructor takes an (unused) instance of this anonymous class Test$1-- which nobody knows exists. Then TestHoldercreates an instance of Test$1and calls thatconstructor, which is accessible (it's default-protected.)

TestHolder需要调用Test. 但它是私有的,实际上不能从另一个类调用。所以编译器玩了一个把戏。它添加了一个Test只有它知道的新的非私有构造函数!该构造函数采用此匿名类的(未使用的)实例Test$1——没人知道它存在。然后TestHolder创建一个实例Test$1并调用构造函数,它是可访问的(它是默认保护的。)

You can use javap -c Test(and javap -c Test\$1, and javap -c Test\$TestHolder) to see the code. It's quite clever, actually!

您可以使用javap -c Test(and javap -c Test\$1, and javap -c Test\$TestHolder) 查看代码。其实还挺聪明的!