运行 来自 Jshell 的回显示例
Run echo example from Jshell
我看过这样一个命令行参数的例子:
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");
我看过这样一个命令行参数的例子:
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");