$0 (Program Name) in Java? Discover main class?

Try this:

    StackTraceElement[] stack = Thread.currentThread ().getStackTrace ();
    StackTraceElement main = stack[stack.length - 1];
    String mainClass = main.getClassName ();

Of course, this only works if you’re running from the main thread. Unfortunately I don’t think there’s a system property you can query to find this out.

Edit: Pulling in @John Meagher’s comment, which is a great idea:

To expand on @jodonnell you can also
get all stack traces in the system
using Thread.getAllStackTraces(). From
this you can search all the stack
traces for the “main” Thread to
determine what the main class is. This
will work even if your class is not
running in the main thread.

Leave a Comment