Java – Calling Java Methods from Shell Scripts


How to execute a Java method from inside shell scripts?

Best Solution

You can only call the main method. Design your main method such that it calls the method you want.

When I say call main method, you don't explicitly invoke it. It's the only entry point to a java program when you invoke it.

If your class looks like:


public class Test {
    public static void main(String[] args) {
        System.out.println("Hello World!");

You can use the following command line to invoke the main from within the directory where you can find com/foo/Test.class (If you're in the classes directory in the structure shown far below):


If you want to do so from a different (See the directory structure far below) directory, then you'll have to set classpath.

java -cp /path/to/classes

Assume the below directory structure for clarity.