How to determine main class at runtime in threaded java application?

后端 未结 10 1018
野的像风
野的像风 2021-01-01 13:37

I want to determine the class name where my application started, the one with the main() method, at runtime, but I\'m in another thread and my stacktrace doesn\'t go all the

10条回答
  •  心在旅途
    2021-01-01 14:26

    Another way to get main class is look for that class on Thread.getAllStackTraces, so you could find it even inside jars, it works on any SDK (Open, Oracle...):

    private static Class mainClass = null;
    
    public static Class getMainClass()
    {
        if (mainClass == null)
        {
            Map threadSet = Thread.getAllStackTraces();
            for (Map.Entry entry : threadSet.entrySet())
            {
                for (StackTraceElement stack : entry.getValue())
                {
                    try
                    {
                        String stackClass = stack.getClassName();
                        if (stackClass != null && stackClass.indexOf("$") > 0)
                        {
                            stackClass = stackClass.substring(0, stackClass.lastIndexOf("$"));
                        }
                        Class instance = Class.forName(stackClass);
                        Method method = instance.getDeclaredMethod("main", new Class[]
                        {
                            String[].class
                        });
                        if (Modifier.isStatic(method.getModifiers()))
                        {
                            mainClass = instance;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            return mainClass;
        }
    }
    

提交回复
热议问题