简体   繁体   中英

is there a way to check if a class has the main method?

I'm trying to get the list of all classes in a project in Java and I would like to identify the class where the main method is located. Is there a way to be able to identify that a class is implementing the main method, without actually looking at the code of the class itself?

I've implemented the following but the return value is always being false. does anyone know why this is happening?

Class<?> c = "edu.tool.parsing.A".getClass();
        boolean hasMain = true;

            try {
                c.getMethod("main", String[].class);
                hasMain=true;
            } catch (SecurityException e) {
                 hasMain = true;
            } catch (NoSuchMethodException e) {
                hasMain=false;
            }

Programmatically:

Class.getClass("com.mycompany.MyClass").getMethod("main", String[].class)

Or alternatively you can use command line utility javap that you can find in your JDK bin directory.

If you have the class name, then you can try to reflect the main method.

Trivial (inclomplete) approach:

private static hasMainMethod(Class<?> clazz) throws Exception {
  Method[] methods = clazz.getMethods();
  for (Mehthod method:methods) {
    if (method.getName().equals("main") {
      // Now we have to verify the method signature!
      return true;
    }
  }
  return false;
}

There may be more than one such class. There may be dozens. Why don't you know the entry point in advance? You might be better off looking at the Main-Class entry in the JAR Manifest.

Load your project in a IDE (I have worked with IDEA) then, add a local run, IDEA will list you all classes with main method.

If you don't have sources and there are just jar files, that's ok, just add the jar files as a library of a project and then create a RUN.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM