如何使用jshell执行Java脚本? [英] How to execute a java script with jshell?

查看:526
本文介绍了如何使用jshell执行Java脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于Java 9即将问世,我们最终可以使用jshell创建Java REPL,我希望有一种方法可以在脚本中添加shebang并让jshell对其进行解释.

Given that Java 9 is upon us and we can finally have a java REPL with jshell I was hoping there was a way to add a shebang to a script and have jshell interpret it.

我尝试创建test.jsh:

#!/usr/bin/env jshell -s
System.out.println("Hello World")
/exit

但是这给出了:

⚡ ./test.jsh
|  Error:
|  illegal character: '#'
|  #!/usr/bin/env jshell -s
|  ^
|  Error:
|  illegal start of expression
|  #!/usr/bin/env jshell -s
|    ^
Hello World

事实证明,OpenJDK https://bugs中对此有增强要求. openjdk.java.net/browse/JDK-8167440 .

It turns out there is an enhancement request for this in OpenJDK https://bugs.openjdk.java.net/browse/JDK-8167440.

还有其他方法吗?

推荐答案

使用

//usr/bin/env jshell --show-version --execution local "$0" "$@"; exit $?

作为test.jsh的第一行. test.jsh脚本可能类似于:

as the first line of test.jsh. The test.jsh script could look like:

//usr/bin/env jshell --show-version "$0" "$@"; exit $?
System.out.println("Hello World")
/exit

当然,命令行选项--show-version是可选的,但会立即反馈该工具正在运行.

The command line option --show-version is optional, of course, but gives immediate feedback that the tool is running.

extra 命令行选项--execution local可防止jshell生成另一个VM.这样可以加快启动时间,并且如果脚本代码引发异常,则本地VM将退出.

The extra command line option --execution local prevents jshell to spawn another VM. This speeds up launch time and if an exception is thrown by your script code, the local VM will exit.

请咨询jshell --helpjshell --help-extra的输出以获取更多选项.

Consult the output of jshell --help and jshell --help-extra for more options.

更新

还要查看 https://github.com/maxandersen/jbang 可以使用Java脚本,它提供了一个简洁的包装器,可用于从命令行运行.java文件.

Also take a look at https://github.com/maxandersen/jbang Having fun with Java scripting, which offers a neat wrapper around running .java files from the command line.

这篇关于如何使用jshell执行Java脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆