This is addressed in 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.
So you are not required to deliver the compiled code as .class
files at all, as long as you have a class loader implementation capable of loading your code representation. Note that on this level, e.g. when passing the mapped data to ClassLoader.defineClass
, the file name of the class file is not present at all. Both specifications, JLS and JVM, consistently use the term “class file” synonym to “a sequence of bytes in the class file format”, rather than “an entry in a file system or zip archive” and therefore, never mention file names at all.
This is also matching the direction Java 9 is going, to deliver class libraries is a custom, potentially optimized library format rather then a zip container full of .class
files.
Still, it would be very discouraged to name the files containing a different representation with a .class
ending.
Your cited statement is a bit odd. It starts with
Giving .class
files the same name as the public class they contain is simply a must,…
but a .class
file doesn’t have to contain a public
class at all. In its current form, it contains at most one class which doesn’t have to be public
. But it may also contain a dummy class to deliver package
meta information or, starting with Java 9, a module specification.
Also, in order to be found by default lookup rules, e.g. using URLClassLoader
, you’re not giving the .class
file the name of the contained class, but rather use its short name and place it in a directory structure/path derived from the package component of its qualified name.
But the second part
… 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.
is correct. As explained above, there’s not even a requirement to deliver class files. Compare to
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.
Note the word “normally”
and
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.
“typically (but not necessarily)”…