获取程序启动类

当程序有多个启动入口时,需要根据不同的启动类来决定方法是否执行,此时就需要获取启动类。

首先根据系统参数 sun.java.command 来获取启动类,如果以jar包方式启动,则获取到的就是jar包名称,此时需要从线程栈中获取main方法或者从jar包的元数据中获取。

java代码如下:

java 复制代码
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

@Slf4j
public class MainClassUtil {

    private static String MAIN_CLASS ;

    /**
     * 忽略的第三方引导类启动
     */
    private static final Set<String> IGNORE_MAIN_CLASS = new HashSet<>(Arrays.asList("org.springframework.boot.loader.JarLauncher"
            , "org.springframework.boot.loader.WarLauncher", "org.springframework.boot.loader.PropertiesLauncher"));

    /**
     * 查找启动类
     * @return 找到返回具体的类名称,否则返回空
     */
    public static String getStartMainClass() {
        if (MAIN_CLASS != null && !MAIN_CLASS.isEmpty()) {
            return MAIN_CLASS;
        }
        // 系统参数
        String clazz = System.getProperty("sun.java.command");
        if (clazz.contains(".jar")) {
            // 通过堆栈跟踪
           clazz = fromStackTrace();
           // 通过 MANIFEST.MF 查找
            if(clazz == null || clazz.isEmpty()){
               clazz = fromJarFile();
            }
        }
        MAIN_CLASS = clazz;
        log.info("start class :{}",MAIN_CLASS);
        return clazz;
    }

    /**
     * 从jar文件 META-INF/MANIFEST.MF 获取
     * @return 启动类,未找到返回空
     */
    private static String fromJarFile() {
        String javaCmd = System.getProperty("sun.java.command");
        String jarName = javaCmd.substring(0,javaCmd.indexOf(".jar") + 4);
        String userDir = System.getProperty("user.dir");
        // 拼接全路径
        if(!jarName.contains("/") && !jarName.contains("\\")){
            jarName = userDir + File.separator + jarName;
        }
        String clazz = null;
        log.info("jarName-------{}",jarName);
        try(JarFile jarFile = new JarFile(jarName)){
            Manifest manifest = jarFile.getManifest();
            Attributes attributes = manifest.getMainAttributes();
            clazz = attributes.getValue("Main-Class");
            if(IGNORE_MAIN_CLASS.contains(clazz)){
                clazz = attributes.getValue("Start-Class");
            }
        }catch (Exception e){
            log.error("jar包解析异常",e);
        }
        return clazz;

    }

    /**
     * 栈内信息查找
     * @return 启动类,未找到返回空
     */
    private static String fromStackTrace(){
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        List<String> mainMethod = new ArrayList<>();
        String methodName, cl;
        for (StackTraceElement stack : stackTrace) {
            methodName = stack.getMethodName();
            cl = stack.getClassName();
            if ("main".equals(methodName) && !IGNORE_MAIN_CLASS.contains(cl)) {
                try {
                    if (hasStandardMain(cl)) {
                        mainMethod.add(cl);
                    }
                } catch (Exception ignore) {
                }
            }
        }
        log.info("包含main方法的类:{}",mainMethod);
        return mainMethod.isEmpty() ? null : mainMethod.get(mainMethod.size() - 1);
    }

    /**
     * 判断是否有main方法
     * @param clazz 类名
     * @return true 有 false 没有
     */
    private static boolean hasStandardMain(String clazz) throws Exception {
        Class<?> aClass = Class.forName(clazz);
        Method main = aClass.getDeclaredMethod("main", String[].class);
        Class<?> returnType = main.getReturnType();
        int modifiers = main.getModifiers();
        return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && (returnType.equals(void.class) || returnType.equals(Void.class)) ;
    }
}
相关推荐
二炮手亮子13 分钟前
浅记java线程池
java·开发语言
一路向北North13 分钟前
Spring Security OAuth2.0(23):分布式系统授权-转发明文给微服务
java·spring·微服务
爱吃牛肉的大老虎2 小时前
rust基础之环境搭建
java·开发语言·rust
tellmewhoisi3 小时前
多版本共用redis的token有效期校验(过期重新登录)
java·redis·缓存
疯狂打码的少年3 小时前
【软件工程】结构化设计:模块独立性与耦合内聚
java·开发语言·笔记·软件工程
乐观的Terry3 小时前
3、数据库设计与领域实体
java·数据库·spring boot·spring cloud·ai编程
C++、Java和Python的菜鸟4 小时前
第4章 后端Web基础(基础知识)
java·开发语言
芷栀夏4 小时前
Java教育平台实战复盘:课程、考试与学习行为分析系统设计
java·开发语言·学习
维基框架4 小时前
维基框架(Wiki-Framework) 1.2.0:Mybatis 升级为主从读写分离
java·后端·架构
Memory_荒年4 小时前
Java函数式接口:把代码变成“拼乐高”的快乐,你体验过吗?
java