Why is an anonymous inner class containing nothing generated from this code?

I’m using polygenelubricants’s smaller snippet.

Remember there’s no concept of nested classes in the bytecode; the bytecode is, however, aware of access modifiers. The problem the compiler is trying to circumvent here is that
the method instantiate() needs to create a new instance of PrivateInnerClass. However, OuterClass does not have access to PrivateInnerClass‘s constructor (OuterClass$PrivateInnerClass will be generated as a package-protected class without a public constructor).

So what can the compiler do? The obvious solution is to change PrivateInnerClass to have a package-protected constructor. The problem here is that this will allow any other code which interfaces with the class to create a new instance of PrivateInnerClass, even though it’s explicitly declared as private!

To try and prevent that, the javac compiler is doing a little trick: instead of making PrivateInnerClass‘s regular constructor visible from other classes, it leaves it as hidden (actually it does not define it at all, but that’s the same thing from outside). Instead, it creates a new constructor which receives an additional parameter of the special type OuterClass$1.

Now, if you look at instantiate(), it calls that new constructor. It actually sends null as the 2nd parameter (of the type OuterClass$1) – that parameter is only used for specifying that this constructor is the one that should be called.

So, why create a new type for the 2nd parameter? Why not use, say, Object? It’s only used to differentiate it from the regular constructor and null is passed anyway! And the answer is that as OuterClass$1 is private to OuterClass, a legal compiler will never allow the user to invoke the special OuterClass$PrivateInnerClass constructor, as one of the required parameter types, OuterClass$1, is hidden.

I’m guessing JDT’s compiler uses another technique to solve the same problem.

Leave a Comment