Can I invoke a java method other than main(String[]) from the command line?

If you don’t have a main function, you can just add one, and if you do, you can just add a series of if-then blocks to the top.

public static void main(String[] args){
    if (args[0].equals("MY_METHOD"))
        callMyMethod();
    else if(args[0].equals("MY_OTHER_METHOD"))
        callMyOtherMethod();
    //... Repeat ad nauseum...
    else {
        //Do other main stuff, or print error message
    }
}

Then, from the command line:

$ java [MyPackage.]MyClass MY_METHOD

Will run your method.

This is pretty hackish – I’m almost sure it’s not what you want to do, but hey, it answers the question, right?

Leave a Comment