Thursday, January 13, 2011

Get program entry point

Today I read the following discussion: How can I determine which class's `main` method was invoked at runtime?


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() {
 Map map = 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