动态加载jar包中的类(方式一)

嘛, 直接上代码

  public static class TestClassLoader extends ClassLoader {
        @Override
        protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {
            if (className.startsWith("com.squareup.okhttp")) {
                return loadOkHttp(className);
            }
            return super.loadClass(className, resolve);
        }

        private Class<?> loadOkHttp(String className) throws ClassNotFoundException {
            String jarPathstr = "";
            String jarPathstr2 = "";
            StringBuilder sb = new StringBuilder();
            sb.append(System.getProperty("user.dir"))
                    .append(File.separator).append("doc").append(File.separator)
                    .append("jar").append(File.separator);
            jarPathstr = sb.toString() + "okhttp-1.2.1.jar";
            jarPathstr2 = sb.toString() + "okhttp-protocols-1.2.1.jar";
            InputStream inputStream = null;
            byte[] clazzs = null;
            try {
                JarFile jarFile = new JarFile(jarPathstr);
                String path = className.replaceAll("\\.", "/") + ".class";
                JarEntry entry = jarFile.getJarEntry(path);
                if (entry == null) {
                    jarFile = new JarFile(jarPathstr2);
                    entry = jarFile.getJarEntry(path);
                }
                if (entry == null) {
                    throw new ClassNotFoundException(className + " Not Found!!");
                }

                inputStream = jarFile.getInputStream(entry);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(buff)) != -1) {
                    baos.write(buff, 0, len);
                }
                baos.close();
                clazzs = baos.toByteArray();
            } catch (IOException e) {

            } finally {
                Util.close(inputStream);
            }

            return defineClass(className, clazzs, 0, clazzs.length);
        }

    }

这个类加载器的作用是, 如果加载的类前缀为 com.squareup.okhttp, 那么就重项目的根目录的doc/jar/下的okhttp-1.2.1.jar和okhttp-protocols-1.2.1.jar中去加载。

 注意jar包是一个归档文件, 里面的实例名称是这样的

 

所以类名className对应的实例名为 className.replaceAll("\\.", "/") + ".class"

posted @ 2016-11-14 18:08  章炎  阅读(1601)  评论(0编辑  收藏  举报