Jason Thompson
Jason Thompson

Reputation: 4833

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.

Upvotes: 0

Views: 65

Answers (2)

Dmitry Ginzburg
Dmitry Ginzburg

Reputation: 7461

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]);

Upvotes: 1

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

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.

Upvotes: 3

Related Questions