`
TRAMP_ZZY
  • 浏览: 132517 次
社区版块
存档分类
最新评论

获取ClassLoader加载目标类的路径

    博客分类:
  • Java
阅读更多

ClassLoader加载的目标类的路径。

public class SrcAdd {
    public static URL getClassLocation(final Class cls) throws MalformedURLException {
        if (cls == null) {
            throw new IllegalArgumentException("null point, 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();
            // 'cs' can be null depending on the classloader behavior:
            if (cs != null) result = cs.getLocation();
            if (result != null) {
                // Convert a code source location into a full class file location
                // for some common cases:
                if ("file".equals(result.getProtocol())) {
                    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);

                }
            }
        }
        if (result == null) {
            // Try to find 'cls' definition as a resource; this is not
            // document.d to be legal, but Sun's implementations seem to         //allow this:
            final ClassLoader clsLoader = cls.getClassLoader();
            result = clsLoader != null ?
                    clsLoader.getResource(clsAsResource) :
                    ClassLoader.getSystemResource(clsAsResource);
        }
        return result;
    }

    public static void main(String[] args) throws ClassNotFoundException, MalformedURLException {
        System.out.println(getClassLocation(Class.forName("java.net.URL")));
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics