This is the closest I can get, and you can take it here. I cannot guarantee that it is really portable, and it will not work if any method calls the main method of another class. Let me know if you find more clean solution.
import java.util.Map.Entry; public class TestMain { public static void main(String[] args) throws ClassNotFoundException { System.out.println(findMainClass()); } public static String findMainClass() throws ClassNotFoundException{ for (Entry<Thread, StackTraceElement[]> entry : Thread.getAllStackTraces().entrySet()) { Thread thread = entry.getKey(); if (thread.getThreadGroup() != null && thread.getThreadGroup().getName().equals("main")) { for (StackTraceElement stackTraceElement : entry.getValue()) { if (stackTraceElement.getMethodName().equals("main")) { try { Class<?> c = Class.forName(stackTraceElement.getClassName()); Class[] argTypes = new Class[] { String[].class };
source share