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.
You have to use this snippet code for object: yourObject. getClass(). getSimpleName();
The main class can have any name, although typically it will just be called "Main".
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.
Yes. Every method or field must belong to a class (or interface/enum).
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
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"; }
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