0

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.

Community
  • 1
  • 1
Jason Thompson
  • 4,643
  • 5
  • 50
  • 74
  • 1
    This is like, one of those things that you *have* to know in order to execute the Java application. Unless you're using something like Spring Boot which gives you a conventional place to define an entry point, I'm not sure what you're getting at here. Something has to know the entry point, and even though it could be divined, it's *concrete*. – Makoto Aug 17 '15 at 21:37
  • How do you start the application, i.e. what do you click or type in a shell? Btw, it is not related to the question you've referenced. – Pawel Veselov Aug 17 '15 at 21:39
  • is it single-threaded? if so create a new exception and look at the bottommost class in the stacktrace. – Nathan Hughes Aug 17 '15 at 21:40

2 Answers2

3

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.

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81
1

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]);
Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48