javaanonymous-class

Different Java compilers generate different class names for the same anonymous class


Names of anonymous classes are generated by concatenating the outer class name with a $ and a number, so e.g. anonymous classes within a class Foo may be generated as Foo$1, Foo$2, etc.

I have made the experience that the Eclipse compiler and the JDK compiler - both set to be compliant with Java 8 - generate the number part differently, i.e. the same anonymous class becomes Foo$2 in Eclipse and Foo$6 with javac.

Is that behaviour backed by the Java standard?

Background: Instances of anonymous classes are stored to a file in chunks with instance.getClass().getName() as an identifier. The assumption was that the class name generation is consistent across different compiler implementations. However, I get different results depending on which compiler was used, and I cannot reliably read the data back that was written with a different implementation.


Solution

  • The Java Language Specification (13.1. The Form of a Binary) says this about the binary names of anonymous classes:

    The binary name of an anonymous class (§15.9.5) consists of the binary name of its immediately enclosing type, followed by $, followed by a non-empty sequence of digits.

    It doesn't say anything about those numbers having any meaning at all - to fulfill the requirements of the Java Language Specification the compiler could use random numbers that change with every compilation.

    Therefore relying on specific values for these numbers is like relying on the ordering of the keys in a HashMap - it can work sometimes and for special cases, but if you want robust software you cannot rely on it.