Programmatically find the main () method in a set of classes

I am working on a project that should take an arbitrary number of java files, compile them, jar them, and then run them. The problem I am facing is this: in which class are we running? Is it possible to find an entry point in a set of classes?

I am ready to make the assumption that these files will have only one entry point.

Here is what I have reviewed so far:

  • Add a helper class to each jar that uses reflection to find a class with main (). To start the jar, call this helper class.
  • Enter the username in your main () class "Basic" or something like that.

Is there a good way to do this? This software is intended for students and novice programmers, so I’m ready to sacrifice reliability for simplicity.

Thanks!

+4
source share
2 answers

One idea from my head could be a user annotation. This is slightly more robust than a naming convention, but simpler than creating a manifest file.

Sort of:

@MainClass public class MyClass { public static void main(String [] args) { // ... } } 

Your tool can scan classes for annotation.

+2
source

The best way to find out which class contains main () is to provide a manifest in the JAR file that calls the main class.

However, your suggestion on how to name your main class in a specific way can also help you teach their conventions or configurations, which is useful to know.

+1
source

All Articles