问题描述
我读了这样的命令行参数示例:
public class Echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
它可以从命令行正常运行,如何从Jshell运行它?
jshell> Echo.main testing
| created variable testing,however,it cannot be referenced until class main is declared
它报告未能被引用的错误。
解决方法
您可以像其他任何静态方法一样调用它:
Echo.main(new String[] { "hello","world" });
完整会话:
$ jshell
| Welcome to JShell -- Version 11.0.8
| For an introduction type: /help intro
jshell> public class Echo {
...> public static void main (String[] args) {
...> for (String s: args) {
...> System.out.println(s);
...> }
...> }
...> }
| created class Echo
jshell> Echo.main(new String[] { "hello","world" });
hello
world
请注意,您可以如下声明您的main
方法:
public static void main(String... args) { ... }
这是与String[] args
语法二进制兼容的,但是允许您按以下方式调用它:
Echo.main("hello","world");