Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 496
ryantm Avatar asked Sep 03 '08 15:09

ryantm


People also ask

Why program is named with class containing main method in Java?

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().

Which is first statement in Java program?

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.

Does every Java program contain at least one class?

classes - A class is a blueprint for building objects in Java. Every Java program has at least one class.

What does every Java program start with?

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.


1 Answers

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.

like image 91
jodonnell Avatar answered Sep 28 '22 14:09

jodonnell