zoukankan      html  css  js  c++  java
  • 判断一个类到底是从哪个jar包中调用的工具类

    项目中使用的jar包较多时,会出现jar冲突的情况,有时候很难判断当前使用的这个类是从哪个jar包中调用的。
    因为一般我们只能看到jar包的名称,不清楚其中的类的目录结构。

    这个类的作用就是说明当前调用的类来自于哪个jar包。

    import java.io.File;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.security.CodeSource;
    import java.security.ProtectionDomain;
    
    public class SystemUtils {
    
        /**
         * 获取一个class类的实际位置
         * @param cls
         * @return
         */
        public static URL getClassLocation(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;
        }
    
    }
  • 相关阅读:
    poj2392 Space Elevator(多重背包问题)
    poj1703 Find them, Catch them(并查集的应用)
    HDU 1867 A + B for you again(KMP算法的应用)
    HDU 1358 Period(kmp简单解决)
    nyoj 460 项链 (区间dp)
    Python内置函数(9)——callable--转载
    Python的hasattr() getattr() setattr() 函数使用方法详解--转载
    python assert 断言详细用法格式
    sam文件格式
    Linux中重定向--转载
  • 原文地址:https://www.cnblogs.com/tq03/p/3958315.html
Copyright © 2011-2022 走看看