通过类反射找到对应的jar位置

来源:互联网 发布:网络丢包怎么解决 编辑:程序博客网 时间:2024/06/01 16:41

在使用构建工具maven开发时,需要找到某个类在那个jar,但是每次一点开就直接源码了,有时候load不到倒是显示了路径,所以这对我造成了一些困扰。

/** * 获取类所在的jar包位置 * */public class ClassLocationUtils {    /**     * 获取类所有的路径     *      * @param cls     * @return     */    public static String where(final Class cls) {        if (cls == null)            throw new IllegalArgumentException("null input: cls");        URL result = null;        final String clsAsResource = cls.getName().replace('.', '/')                .concat(".class");        final ProtectionDomain pd = cls.getProtectionDomain();        if (pd != null) {            final CodeSource cs = pd.getCodeSource();            if (cs != null)                result = cs.getLocation();            if (result != null) {                if ("file".equals(result.getProtocol())) {                    try {                        if (result.toExternalForm().endsWith(".jar")                                || result.toExternalForm().endsWith(".zip"))                            result = new URL("jar:"                                    .concat(result.toExternalForm())                                    .concat("!/").concat(clsAsResource));                        else if (new File(result.getFile()).isDirectory())                            result = new URL(result, clsAsResource);                    } catch (MalformedURLException ignore) {                    }                }            }        }        if (result == null) {            final ClassLoader clsLoader = cls.getClassLoader();            result = clsLoader != null ? clsLoader.getResource(clsAsResource)                    : ClassLoader.getSystemResource(clsAsResource);        }        return result.toString();    }}

测试

    @Test    public void show(){        String location=ClassLocationUtils.where(AnnotationVisitor.class);        System.out.println(location);    }

结果

jar:file:/I:/MAVEN_LIb/org/springframework/spring-core/4.2.5.RELEASE/spring-core-4.2.5.RELEASE.jar!/org/springframework/asm/AnnotationVisitor.class
1 0