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

时间:2011-11-26 00:27:57

标签: java

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

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

1 个答案:

答案 0 :(得分:8)

这是我能得到的最接近的你可以从这里拿到它。我不能保证它是真正可移植的,如果任何方法调用另一个类的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<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;
    }
}