为什么classname $ 1.class在这种情况下生成? [英] Why does classname$1.class generate in this situation?
问题描述
我写了以下代码来实现Singleton模式:
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;
}
}
当编译此文件时,应生成Test。类和Test $ TestHolder.class,但它也生成Test $ 1.class。这没有意义。
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?
推荐答案
类 TestHolder
需要调用 Test
中的私有构造函数。但它是私有的,并且实际上不能从另一个类调用。所以编译器扮演一个伎俩。 向 Test
添加了一个新的非私有构造函数,它只知道!构造函数接受此匿名类的一个(未使用)实例 Test $ 1
- 没有人知道存在。然后 TestHolder
创建 Test $ 1
的实例并调用构造函数,它的默认保护。)
Class TestHolder
needs 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 Test
which only it knows about! That constructor takes an (unused) instance of this anonymous class Test$1
-- which nobody knows exists. Then TestHolder
creates an instance of Test$1
and calls that constructor, which is accessible (it's default-protected.)
您可以使用 javap -c Test
(和 javap -c Test\ $ 1
和 javap -c Test\ $ TestHolder
)来查看代码。这是相当聪明,实际上!
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!
这篇关于为什么classname $ 1.class在这种情况下生成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!