简体   繁体   中英

How do I figure out which class was executed as the main class?

Ultimately what I want is something similar to the answer from this question:

Find where java class is loaded from

There's one twist. Unlike the examples, I don't know what class will contain the main method at compile time. But if I knew which class was called first, I could then locate where my application was executed from.

So my question is this: How do I discover what class contains the main method that was called to execute my java application?

EDIT (Clarification):

I want to have a library to know the "name" of the application I'm running. So if I type in java -cp ... MyMainClass and my main class happened to live in the folder /usr/something/myApp/lib/MyMainClass.jar then I could report back "myApp". This would be a fallback default option to infer my program's name.

If you're in the main thread of the program, you can do this:

StackTraceElement[] stackTrace = new Exception().getStackTrace();
String className = stackTrace[stackTrace.length - 1].getClassName();

As @Makoto says, it might be useful with an explanation of why you need to do this; there are probably better ways, depending on how you're starting the application.

To get the entry point, not depending on the thread, you can retrieve all stacktraces and choose the top point in the one with id == 1 , for example (Java 8):

StackTraceElement[] stackTrace = Thread.getAllStackTraces()
        .entrySet()
        .stream()
        .filter(entry -> entry.getKey().getId() == 1)
        .findFirst().get()
        .getValue();
System.out.println(stackTrace[stackTrace.length - 1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM