简体   繁体   中英

Java: multiple inner classes generated from Singleton Holder pattern

I have a pretty simple singleton that uses holder pattern (I've shown just the pattern, not other details):

public class Foo
{
    private static class FooHolder
    {
        private static final Foo INSTANCE = new Foo();
    }

    public static Foo getInstance()
    {
        return FooHolder.INSTANCE;
    }
}

When I compile this class through Eclipse 1.6 compiler , it generates two classes: Foo.class and Foo$FooHolder.class . But when I compile it through Maven and JDK 1.6 compiler , it generates an additional class: Foo$1.class and that class is pretty much empty.

I'm trying to understand why this happens. I cannot provide more details on code due to restrictions.

While java allows access to private members of other classes in the same .java the JVM doesn't support this.

Instead the compiler generates code which gives secret access to these member via generated accessor methods eg access$010() or generated sub - classes. Exactly how each compiler does it is an implementation detail.

I am pretty sure Oracle JDK 7 doesn't do this.

Btw, using an Enum instead world be simpler and create less classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM