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.
Whenever the program is called, it automatically executes the main() method first. The main() method can appear in any class that is part of an application, but if the application is a complex containing multiple files, it is common to create a separate class just for main().
The main statement is the entry point to most Java programs. The exceptions are applets, programs that are run on a web page by a web browser; servlets, programs run by a web server; and apps, programs run by a mobile device. Most programs you write during upcoming hours use main as their starting point.
classes - A class is a blueprint for building objects in Java. Every Java program has at least one class.
Every Java program is a class. The program starts with the name of the class. This name must be the same name as the . java file in your folder.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With