How to determine main class at runtime in threaded java application?

Erik R. picture Erik R. · Jun 2, 2009 · Viewed 15.7k times · Source

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.

Answer

Bruno Eberhard picture Bruno Eberhard · Nov 7, 2014

See the comments on link given by Tom Hawtin. A solution is these days is (Oracle JVM only):

public static String getMainClassAndArgs() {
    return System.getProperty("sun.java.command"); // like "org.x.y.Main arg1 arg2"
}

Tested only with Oracle Java 7. More information about special cases: http://bugs.java.com/view_bug.do?bug_id=4827318