tags:

views:

3060

answers:

4

Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.

+19  A: 

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.

jodonnell
+3  A: 

Also from the command line you could run the jps tool. Sounds like a

jps -l

will get you what you want.

polarbear
+6  A: 

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.

John Meagher
It is possible for the main thread to stop running but the application still continues (other non-daemon threads). This likely happens in many GUI/Swing applications since the common idiom is for the main thread to invoke on EDT to create the first frame and then terminate.
Kevin Brock
A: 

Or you could just use getClass(). You can do something like:

public class Foo
{
    public static final String PROGNAME = new Foo().getClass().getName();
}

And then PROGNAME will be available anywhere inside Foo. If you're not in a static context, it gets easier as you could use this:

String myProgramName = this.getClass().getName();
Adam