3

I read such a command line arguments example:

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

It runs properly from command line, how could I run it from Jshell?

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

It report error that failed to be referenced.

Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

1 Answers1

2

You invoke it as any other static method:

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

Full session:

$ 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

Note that you can declare your main method as follows:

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

This is binary compatible with String[] args syntax, but would allow you to invoke it as follows:

Echo.main("hello", "world");
aioobe
  • 413,195
  • 112
  • 811
  • 826