Finding the main class
Can I define the main class of my application? The one that is either given on the command line or loaded from the jar given on the command line?
If that's not possible, why not?
EDIT: Maybe I was not clear. I know there can always be many entry points in my application, but while the application is running, only one entry point was used to launch the current JVM. This is what I need to know about.
a source to share
First of all, an application can have multiple entry points . It's just a class that contains a public static main method with an argument type String[]
.
So the short answer is, no, there may be multiple possible entry points for a set of classes.
If you want to list all the entry points of the application, you just have to loop over the classes and look for such a main method.
If you create a "runnable jar-file" file , an entry similar to this will appear in the manifest file
Main-Class: MyPackage.MyClass
which defines the main class of the application.
a source to share
One possibility would be to use the thread stack trace and look for the starting 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();
It will also help you understand how difficult it is. The initial main thread doesn't even have to start. You can even try to put this check directly in a static method of main
one of your classes and it still doesn't work correctly. It is possible to execute the main method from another class through reflection, and that the initiating method may already be running on a thread other than the initiating thread.
For Swing applications, the standard idiom is to initiate the initial main thread after activating the first form. Therefore, in these cases, you can be sure that the main class and the initiating thread no longer work.
a source to share
You can get a stack trace like
StackTraceElement[] stack = new Throwable().getStackTrace();
In a command line application, the last element will be the main class:
System.out.println(stack[stack.length - 1].getClassName());
This is trickier for servlets, applets, or other plugins (you have to traverse the stack looking for classes with the same ClassLoader
as the current thread.)
a source to share