Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private inner class synthesizes unexpected anonymous class

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?

like image 924
John Calsbeek Avatar asked Aug 12 '09 17:08

John Calsbeek


1 Answers

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

Take a look at this question for details.

like image 159
ChssPly76 Avatar answered Sep 20 '22 02:09

ChssPly76