The problem was to distinguish the entry point to the program, i.e. which class' main was used to start the program. The suggestion was obvious:
public static getMainClassName() { StackTraceElement[] elem = new Exception().getStackTrace(); return elem[elem.length - 1].getClassName(); }
This solution is fine but it is correct for main thread only. How to detect the program entry point from other thread? Fortunately we have method
getAllStackTraces()
available in class Thread
since java 1.5. So, the solution is to iterate over all threads, detect the main thread and return last element of its stack trace:private static String getMainClassName() { Mapmap = Thread.getAllStackTraces(); for (Map.Entry entry : map.entrySet()) { Thread thread = entry.getKey(); if ("main".equals(thread.getName()) && "main".equals(thread.getThreadGroup().getName())) { StackTraceElement[] trace = entry.getValue(); return trace[trace.length - 1].getClassName(); } } return null; }
This method can be called from any thread in the application. But it also has its limitation. Method
getAllStackTraces()
returns currently running threads. If main thread was terminated before the method is called the program entry point can not be found.
No comments:
Post a Comment