从Java代码中查找主类名称的便携方法

有没有办法从该JVM中运行的任意代码中找到用于启动当前JVM的主类的名称?

任意,我的意思是代码不一定在主线程中运行,或者可能在main调用之前在主线程中运行(例如,用户提供的java.system.classloader中的代码,它在main之前运行因为它用于加载main) – 所以检查调用堆栈是不可能的。

这是我能得到的最接近的你可以从这里得到它。我不能保证它是真正可移植的,如果任何方法调用另一个类的主方法它将无法工作。让我知道你是否找到更干净的解决方案

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 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; } }