Search code examples
javaprogram-entry-pointmain-method

Programmatically find default main() method from multiple main() methods using java


Given the following class, I am trying to find program's main entry point:

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

    public static void main(String a, String b){
        // ...
    }

    public void main(int a){
        // ...
    }
}

Any help appreciated, thanks.


Solution

  • Find the method named main, which is public, static, returns void, and takes a String array as argument.

    The Class.getDeclaredMethod() can be used to do that. And you just need to filter the returned method to only keep it if it's public, static, and returns void. The getModifiers() and getReturnType() methods of the Method class can be used to do that.