Java 11 : Executing Source File via Shebang is not working

标签 java shebang java-11

我想看看前两天发布的 java 11 的一些新特性。 JEP 330声明我可以在不编译的情况下启动 Java-Source-Code-Program。 它还应该支持 Shebang-Files 的使用。

因此我编写了这个小的 Hello-World 程序 Test.java:

#!/opt/java/jdk-11/bin/java --source 11

public class Test
{
    public static void main(String[] args)
    {
        System.out.println("Hello World!");
    }
}

downloaded JDK 11并将其提取到 /opt/java。 因此,Shebang 本身正在发挥作用。 IE。执行 /opt/java/jdk-11/bin/java --version 给我

openjdk 11 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)

在使 Test.java 可执行后(使用 chmod +x Test.java)执行失败。 IE。 ./Test.java 给我:

./Test.java:1: error: illegal character: '#'
#!/opt/java/jdk-11/bin/java --source 11
^
./Test.java:1: error: class, interface, or enum expected
#!/opt/java/jdk-11/bin/java --source 11
^
2 errors
error: compilation failed

只要我从 Test.java 中删除 Shebang-Line 并使用 /opt/java/jdk-11/bin/java --source 11 Test.java< 启动它 一切正常,我得到了预期的输出:Hello World!

我的机器正在运行 Ubuntu 17.04。 我已将 javac 链接到 JDK 11 中的那个(即执行 javac -version 给出 javac 11)。

最佳答案

文件名不得以 .java 结尾,以便 java 可执行文件忽略 shebang 行。您可以使用不同的扩展名,或者根本没有扩展名(这是他们在 JEP 示例中所做的,也是我推荐的)。

来自 JEP 330 (强调):

When the launcher reads the source file, if the file is not a Java source file (i.e. it is not a file whose name ends with .java) and if the first line begins with #!, then the contents of that line up to but not including the first newline are ignored when determining the source code to be passed to the compiler. The content of the file that appears after the first line must consist of a valid CompilationUnit as defined by §7.3 in the edition of the Java Language Specification that is appropriate to the version of the platform given in the --source option, if present, or the version of the platform being used to run the program if the --source option is not present.

不需要特别以“.sh”结尾;此外,这可能会产生误导,因为该文件实际上并不是一个 shell 脚本。

关于Java 11 : Executing Source File via Shebang is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52530470/

相关文章:

linux - bash 和 linux 内核中的 Shebang 行限制

java - 如何启用单击按钮格式并通过窗口增加文本大小

java - 在 clojure 中处理 JavaOptional<T>

java - java中Integer和String的常用属性类型

java - Powermock 调用真正的方法而不是 spy 方法

reactjs - 如何配置带有Shebang Loader的Webpack忽略Hashbang将Cesium React组件导入Typescript React组件

java - 如何判断 Java 中的线程池是否空闲

linux - 如何将 shebang 行批量添加到目录中的所有脚本?

java - 为什么使用-XX :TraceBytecodes记录的java程序的执行字节码存在差异

java - 从 WSL 中完全卸载 openjdk-11