java 语言规范上下文中的 "binary name of a class" 是什么?

What is "binary name of a class" in java language specification context?

在阅读 class 加载程序时,我遇到了二进制名称的概念,但我不太了解它。

你能解释一下 java class 的二进制名称是什么以及为什么 package + className 不够用吗(我猜是因为内部 classes ,但这是唯一的原因)吗? 谢谢

内心class并不是唯一的原因;本地 classes、匿名 classes 和类型变量也有二进制名称。

来自Java语言规范(§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.

至于二进制名称的用途,这在同一节中给出:

A reference to another class or interface type must be symbolic, using the binary name of the type.

也就是说,在编译的字节码中 classes 是通过它们的二进制名称引用的,而不仅仅是它们的规范名称。

一个很好的理由是两个 class 可以有相同的规范名称:例如,规范名称 A.B 可以是一个 class 命名为 B 在名为 A 的包中,或名为 B 的 class 声明为默认包中名为 A 的 class 的内部 class .这两个 classes 的二进制名称分别是 A.BA$B

另一个原因是有些 class 根本没有规范名称 - 例如,“本地 class 没有规范名称。” (§6.7).