While reading about class loaders, i came a cross the concept of binary name, but i didn't understand it quite well.
Could you please explain what is binary name of a java class and why package + className does not suffice (i guess because of inner classes, but is this the only reason)? Thanks
Inner classes are not the only reason; local classes, anonymous classes, and type variables also have binary names.
From the Java Language Specification (§13.1):
The class or interface must be named by its binary name, which must meet the following constraints:
The binary name of a top level type (§7.6) is its canonical name (§6.7).
The binary name of a member type (§8.5, §9.5) consists of the binary name of its immediately enclosing type, followed by $, followed by the simple name of the member.
The binary name of a local class (§14.3) consists of the binary name of its immediately enclosing type, followed by $, followed by a non-empty sequence of digits, followed by the simple name of the local class.
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.
The binary name of a type variable declared by a generic class or interface (§8.1.2, §9.1.2) is the binary name of its immediately enclosing type, followed by $, followed by the simple name of the type variable.
The binary name of a type variable declared by a generic method (§8.4.4) is the binary name of the type declaring the method, followed by $, followed by the descriptor of the method (JVMS §4.3.3), followed by $, followed by the simple name of the type variable.
The binary name of a type variable declared by a generic constructor (§8.8.4) is the binary name of the type declaring the constructor, followed by $, followed by the descriptor of the constructor (JVMS §4.3.3), followed by $, followed by the simple name of the type variable.
As for the purpose of binary names, this is given in the same section:
A reference to another class or interface type must be symbolic, using the binary name of the type.
That is, in the compiled bytecode classes are referred to by their binary name, not simply their canonical name.
One good reason for this is that two classes can have the same canonical name: for example, the canonical name A.B
could be a class named B
in a package named A
, or a class named B
declared as an inner class of a class named A
in the default package. The binary names of these two classes would be A.B
and A$B
respectively.
Another reason is that some classes do not have canonical names at all - for example, "A local class does not have a canonical name." (§6.7).