Why does classname$1.class generate in this situat

2019-03-14 14:36发布

This question already has an answer here:

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?

1条回答
一夜七次
2楼-- · 2019-03-14 15:06

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.)

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!

查看更多
登录 后发表回答