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?


If you install a REPL for a JVM language (Groovy probably takes the least work to get started with), then you can invoke Java methods at the REPL prompt (Groovy's is called groovysh). groovysh has some odd features (my least favorite bit is that declaring variables with def doesn't do what you'd think it should) but it's still really useful. It's an interesting feature that Groovy doesn't respect privacy, so you can call private methods and check the contents of private variables.

Groovy installs include groovysh. Download the zip file, extract it somewhere, add the location of the bin directory to the path and you're good to go. You can drop jars into the lib folder, for the code you're running and libraries used by that code, and Groovy will find them there.


Here is a bash function that lets you do just that:

function javae {
  TDIR=`mktemp -d`
  echo "public class Exec { public static void main(String[] args) throws Exception { " $1 "; } }" > $TDIR/Exec.java && javac $TDIR/Exec.java && java -cp $CLASSPATH:$TDIR Exec;
  rm -r $TDIR;
}

Put that in ~/.bashrc and you can do this:

javae 'System.out.println(5)'

Or this:

javae 'class z { public void run() { System.out.println("hi"); } }; (new z()).run()'

It's a hack of course, but it works.

Tags:

Java

Methods