Home > Back-end >  Why does an anonymous inner class have such type when I disassemble the class file using javac?
Why does an anonymous inner class have such type when I disassemble the class file using javac?

Time:11-09

When I disassembled the code given below, I noticed that the TestClass's anonymous inner class in constant pool is displayed as 'AnonymousTestApp$1', but shouldn't it be 'TestClass$1'?

The code:

public class AnonymousTestApp {
    public static void main(String[] args) {
        TestClass tc = new TestClass(){

        };
    }
}

Compiled using Oracle JDK 17 and disassembled using 'javap -c -p -v'.

CodePudding user response:

First: The "name" of that class is effectively irrelevant, since it's an anonymous name, i.e. it's generated and not for the developer to know or care about.

Second: AnonymousTestApp$1 is used (by this compiler, that's not defined in the standard) to indicate the first anonymous subclass contained in the code of AnonymousTestApp.

TestClass$1 would be the name if the anonymous class was defined inside of TestClass.

Think about this problem: If multiple classes in the same package created anonymous subclasses of the same base class, how would they coordinat to avoid name clashes? Using the name of the current top-level class as the prefix avoids such a potential clash.

While $ can be apart of a normal Java identifier, it is explicitly discouraged in the JLS:

The dollar sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

  • Related