Uruchom przykład echa z Jshell [duplicate]

Sep 08 2020

Czytałem taki przykład argumentów wiersza poleceń:

public class Echo {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}

Działa poprawnie z wiersza poleceń, jak mogę go uruchomić z Jshell?

jshell> Echo.main testing
|  created variable testing, however, it cannot be referenced until class main is declared

Zgłasza błąd, do którego nie można się odwołać.

Odpowiedzi

2 aioobe Sep 08 2020 at 15:51

Wywołujesz ją jak każdą inną metodę statyczną:

Echo.main(new String[] { "hello", "world" });

Pełna sesja:

$ 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

Zauważ, że możesz zadeklarować swoją mainmetodę w następujący sposób:

public static void main(String... args) { ... }

Jest to binarnie zgodne ze String[] argsskładnią, ale pozwala wywołać je w następujący sposób:

Echo.main("hello", "world");