ict1991
ict1991

Reputation: 2100

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;
            }

Upvotes: 0

Views: 1512

Answers (4)

user207421
user207421

Reputation: 310909

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.

Upvotes: 0

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

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.

Upvotes: -1

AlexR
AlexR

Reputation: 115338

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.

Upvotes: 8

Andreas Dolk
Andreas Dolk

Reputation: 114777

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;
}

Upvotes: 3

Related Questions