Java – Calling Java Methods from Shell Scripts

javashell

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:

package com.foo;

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):

java com.foo.Test

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 com.foo.Test

Assume the below directory structure for clarity.

-path
    -to
        -classes
            -com
                -foo
                    >Test.class