Java 11 在使用 'java' 编译 class 时不会生成 .class 文件

Java 11 does not produce a .class file when compiling the class with 'java'

我安装了 Java 11。当我 运行 命令 java <filename.java> 编译和 运行ning 代码时,它编译并 运行s 程序,在 CMD 中显示输出,但它没有生成任何 .class 文件。

你能解释一下为什么它不生成 .class 文件吗?

看看JEP 330

由于Java11,java FileName.java编译运行FileName.java;然而,编译发生在“幕后”,没有明确生成相应的 .class 文件。相反,它直接将相应的 byte-code 加载到 JVM 实例中。

动机

Single-file programs (where the whole program fits in a single source file) - are common in the early stages of learning Java, and when writing small utility programs. In this context, it is pure ceremony to have to compile the program before running it. In addition, a single source file may compile to multiple class files, which adds packaging overhead to the simple goal of "run this program". It is desirable to be able to run the program directly from source with the java launcher:

java HelloWorld.java

如果你想将.class文件作为输出,你仍然应该使用javac,如:

javac FileName.java