从Java代码中查找主类名称的便携方法 [英] Portable way to find name of main class from Java code

查看:102
本文介绍了从Java代码中查找主类名称的便携方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any way to find the name of the main class used to launch the current JVM, from arbitrary code running in that JVM?

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

By arbitrary, I mean that the code is not necessarily running in the main thread, or may be running in the main thread before main has even been called (e.g., code in a user-supplied java.system.classloader, which runs before main since it's used to load main) - so examining the call stack is not possible.

推荐答案

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

This is the closest I can get and you can take it from here.I can not guarantee that it is truly portable and it will not work if any method is invoking 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;
    }
}

这篇关于从Java代码中查找主类名称的便携方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆