A portable way to find the name of a main class from Java code

Is it possible to find the name of the main class used to run the current JVM from arbitrary code running in this JVM?

By arbitrary, I mean that the code does not necessarily work in the main thread or can be executed in the main thread before main was even called (for example, the code in the user-supplied java.system.classloader, which runs before the main, because it is used to boot main), so checking the call stack is not possible.

+2
source share
1 answer

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 { /** * @param args * @throws ClassNotFoundException */ 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 }; //This will throw NoSuchMethodException in case of fake main methods c.getDeclaredMethod("main", argTypes); return stackTraceElement.getClassName(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } } } } return null; } } 
+8
source

All Articles