Hoe can I detect the main class of my application? The one, which is either given on the command line or loaded from the jar given at the command line?
If this is not possible, why not?
EDIT: Maybe I wasn't clear. I know there always can be many entry points into my app, but while the app is running, there was only one entry point used to start the current JVM. This is the one I need to know of.
First of all, an application can have several entry points. It is simply a class that contains a public static method called main with the argument type String[].
So, short answer, no, there may be several possible entry points of a set of classes.
If you want to list all entry points of an application, you would simply need to iterate over the classes and look for such main method.
If you create a "runnable jar-file" however, there will be an entry in the Manifest file looking like
Main-Class: MyPackage.MyClass
which specifies the main class of the application.
One possibility would be to use the stack trace of a thread and look for the initiating class. However, this can only work if the trace is on the initial main thread.
Throwable t = new Throwable();
StackTraceElement[] elems = t.getStackTrace();
String initClass = elems[elems.length - 1].getClassName();
String initMethod = elems[elems.length - 1].getMethodName();
This will also help you understand how difficult this can be. The initial main thread does not even have to be running any more. You could even attempt to put this check directly in the main static method of one of your classes and still not work right. It is possible to execute a main method from another class through reflection and that initiating method may itself already be running on a thread other than the initiating thread.
For Swing applications, the standard idiom is to let the initiating main thread terminate after activating the first form. So in these cases you can be certain that the main class and initiating thread are no longer running.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With