Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 717
Erik R. Avatar asked Jun 02 '09 14:06

Erik R.


People also ask

How do I find my runtime class name?

You have to use this snippet code for object: yourObject. getClass(). getSimpleName();

What is main class name in Java?

The main class can have any name, although typically it will just be called "Main".

How do I run a Java main class?

Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.

Is main method belongs to any class?

Yes. Every method or field must belong to a class (or interface/enum).


2 Answers

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: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4827318

like image 103
Bruno Eberhard Avatar answered Oct 17 '22 02:10

Bruno Eberhard


The JAVA_MAIN_CLASS environment value isn't always present depending on the platform. If you just want to get a name of the "main" class that started your Java process, you can do this:

  public static String getMainClassName()   {     StackTraceElement trace[] = Thread.currentThread().getStackTrace();     if (trace.length > 0) {       return trace[trace.length - 1].getClassName();     }     return "Unknown";   }  
like image 26
Dave Avatar answered Oct 17 '22 02:10

Dave