在阅读类加载器时,我对二进制名称的概念有所了解,但我不太了解它。
你能解释一下java类的二进制名称是什么,为什么包+类名不够(我猜是因为内部类,但这是唯一的原因)?
谢谢
最佳答案
内部类不是唯一的原因;本地类、匿名类和类型变量也有二进制名称。
来自 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.
也就是说,在编译的字节码中,类是通过它们的二进制名称引用的,而不仅仅是它们的规范名称。
一个很好的理由是两个类可以具有相同的规范名称:例如,规范名称
A.B
可以是一个名为 B
的类在名为 A
的包中,或名为 B
的类声明为名为 A
的类的内部类在默认包中。这两个类的二进制名称将是 A.B
和 A$B
分别。另一个原因是某些类根本没有规范名称——例如,“本地类没有规范名称”。 ( §6.7 )。
关于java - java语言规范上下文中的 "binary name of a class"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59275716/