我学到了here即使这是最佳实践并且大多数编译器都要求您这样做,但 .class
并不那么严格至少从语言规范的角度来看,以它们包含的公共(public)类命名的文件。
我搜索了 JLS 和 JVM 规范,但无法找到讨论该主题的实际章节。我觉得很奇怪,这个问题根本没有得到处理。
Oracle 官方文档(如果存在)可以在哪里确认或揭穿以下陈述?
Giving
.class
files the same name as the public class they contain - whether they do - is simply a must, but according to the JLS this is not that strict. From the JLS's perspective, it is left to the compiler to choose whether to set such a restriction or not.
最佳答案
此问题已在 JLS §13.1., The Form of a Binary 中解决:
Programs must be compiled either into the
class
file format specified by The Java Virtual Machine Specification, Java SE 8 Edition, or into a representation that can be mapped into that format by a class loader written in the Java programming language.
因此,您根本不需要将编译后的代码作为 .class
文件提供,只要您有一个能够加载代码表示的类加载器实现即可。请注意,在这个级别上,例如将映射数据传递给 ClassLoader.defineClass
时,类文件的文件名根本不存在。 JLS 和 JVM 这两个规范都一致使用术语“类文件”,它是“类文件格式中的字节序列”的同义词,而不是“文件系统或 zip 存档中的条目”,因此,永远不要在全部。
这也符合 Java 9 的发展方向,以自定义的、可能优化的库格式提供类库,而不是充满 .class
文件的 zip 容器。
不过,我们非常不鼓励以 .class
结尾来命名包含不同表示形式的文件。
你引用的说法有点奇怪。它开始于
Giving
.class
files the same name as the public class they contain is simply a must,…
但是 .class
文件根本不必包含 public
类。在其当前形式中,它最多包含一个类,该类不必是public
。但它也可能包含一个虚拟类来传递包
元信息,或者从 Java 9 开始,传递一个模块规范。
此外,为了通过默认查找规则找到,例如使用 URLClassLoader
,您不会为 .class
文件提供所包含类的名称,而是使用其短名称并将其放置在派生于的目录结构/路径中其限定名称的包组件。
但第二部分
… but according to the JLS this is not that strict. From the JLS's perspective, it is left to the compiler to choose whether to set such a restriction or not.
是正确的。如上所述,甚至不需要提供类文件。比较
JLS §1., Introduction :The Java programming language is normally compiled to the bytecode instruction set and binary format defined in The Java Virtual Machine Specification, Java SE 8 Edition.
注意“通常”这个词
和
JVMS §2.1., The class File Format :Compiled code to be executed by the Java Virtual Machine is represented using a hardware- and operating system-independent binary format, typically (but not necessarily) stored in a file, known as the
class
file format.
“通常(但不一定)”...
关于.class 文件的 Java 语言命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46811014/