All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.azbh111.utils.java.io.jar.JarUtils Maven / Gradle / Ivy

The newest version!
package com.github.azbh111.utils.java.io.jar;

import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.security.ProtectionDomain;

/**
 * @author pyz
 * @date 2018/9/15 上午10:46
 */
public class JarUtils {
    private static final String osName = System.getProperty("os.name").toLowerCase();

    /**
     * 获取类所属的jar
     * 例如:
     * 在IDE环境中获取开发中的类 /Users/admin/project/ruoshui/xxx/out/production/classes/
     * 在IDE环境中获取jar中的类 /Users/admin/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/2.1.5.RELEASE/939061a385b4e30e115978d78a7412fb984674df/spring-boot-2.1.5.RELEASE.jar
     * 运行SpringBoot的bootJar进行调用 file:/Users/admin/project/ruoshui/xxx/build/libs/xxx-0.0.1.jar!/BOOT-INF/classes!/
     * 运行SpringBoot的bootJar进行调用(jar in jar) file:/Users/admin/project/ruoshui/xxx/build/libs/xxx-0.0.1.jar!/BOOT-INF/lib/spring-boot-2.1.5.RELEASE.jar!/
     *
     * @param clazz
     * @return
     * @throws Exception
     */
    public static Path getJar(Class clazz) throws Exception {
        ProtectionDomain protectionDomain = clazz.getProtectionDomain();
        CodeSource codeSource = protectionDomain.getCodeSource();
        URI location = (codeSource != null) ? codeSource.getLocation().toURI() : null;
        String path = (location != null) ? location.getSchemeSpecificPart() : null;
        if (path == null) {
            throw new IllegalStateException("Unable to determine code source archive");
        }
        if (osName.contains("windows") && path.startsWith("/")) {
            path = path.substring(1);
        }
        return Paths.get(path);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy