gpt4 book ai didi

Java 11 : Executing Source File via Shebang is not working

转载 作者:太空狗 更新时间:2023-10-29 22:53:35 25 4
gpt4 key购买 nike

我想看看前两天发布的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com