I want to determine the class name where my application started, the one with the main() method, at runtime, but I'm in another thread and my stacktrace doesn't go all the way back to the original class.
I've searched System properties and everything that ClassLoader has to offer and come up with nothing. Is this information just not available?
Thanks.
I suggest to put this information into a system property. This is usually simple to do when you start your application from a script.
If you can't do that, I suggest to set the property in the main() method of every application. The most simple way here would be to have every app derive it's "main class" from a common base class and run an init step in there. I often do this for command line processing:
Another way to get main class is look for that class on Thread.getAllStackTraces, so you could find it even inside jars, it works on any SDK (Open, Oracle...):
The JAVA_MAIN_CLASS environment value isn't always present depending on the platform. If you just want to get a name of the "main" class that started your Java process, you can do this:
I figured it out. Can anyone tell me if this environment variable will always be around in other java implementations across operating systems? This on Oracle JVM yields a String like "org.x.y.ClassName"
See the comments on link given by Tom Hawtin. A solution is these days is (Oracle JVM only):
Tested only with Oracle Java 7. More information about special cases: http://bugs.java.com/view_bug.do?bug_id=4827318
How about something like:
This will give you something like
The main thread is probably not guarenteed to be called
"main"
though - might be better to check for a stack trace element that contains(main
Edit if the main thread has exited, this is no good!