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

后端 未结 10 977
野的像风
野的像风 2021-01-01 13:37

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

10条回答
  •  粉色の甜心
    2021-01-01 14:39

    How about something like:

    Map stackTraceMap = Thread.getAllStackTraces();
    for (Thread t : stackTraceMap.keySet())
    {
        if ("main".equals(t.getName()))
        {
            StackTraceElement[] mainStackTrace = stackTraceMap.get(t);
            for (StackTraceElement element : mainStackTrace)
            {
                System.out.println(element);
            }
        }
    }
    

    This will give you something like

    java.lang.Object.wait(Native Method)
    java.lang.Object.wait(Object.java:231)
    java.lang.Thread.join(Thread.java:680)
    com.mypackage.Runner.main(Runner.java:10)
    

    The main thread is probably not guarenteed to be called "main" though - might be better to check for a stack trace element that contains (main

    Edit if the main thread has exited, this is no good!

提交回复
热议问题