Detect main class
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.
You can get a stack trace, e.g.
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());
It is more complicated for servlets, applets or other plugins (you have to iterate through the stack, looking for classes with the same ClassLoader
as the current thread.)
This is pretty clean: Pass in the class name as a program argument from the command line. From there, you can instantiate it using reflection, etc.
java foo.bar.MyMainClass foo.bar.MyMainClass
精彩评论