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

后端 未结 8 499
夕颜
夕颜 2020-11-30 09:35

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

相关标签:
8条回答
  • 2020-11-30 10:24

    You cannot invoke even the main method from the command. The JVM invokes the main method. Its just a convention. It always needs to be "public static void main".

    What is your use case?

    0 讨论(0)
  • 2020-11-30 10:26

    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?

    0 讨论(0)
提交回复
热议问题