运行时找到main方法所在的类

Posted yejg1212

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了运行时找到main方法所在的类相关的知识,希望对你有一定的参考价值。

private Class<?> deduceMainApplicationClass() {
    try {
        StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if ("main".equals(stackTraceElement.getMethodName())) {
                return Class.forName(stackTraceElement.getClassName());
            }
        }
    }
    catch (ClassNotFoundException ex) {
        // Swallow and continue
    }
    return null;
}

这个是SpringApplication中获取main class的方法。一直觉得这种方式有点“挫”,^_^,没想到Spring也这么用,不知道还有没有其他更好的办法。

以上是关于运行时找到main方法所在的类的主要内容,如果未能解决你的问题,请参考以下文章