类加载器

作者: 砺豪 | 来源:发表于2017-01-22 01:21 被阅读32次

    源码附送

    java类加载为什么需要双亲委派模型这样的往返模式?

    • 委派模型对于安全性是非常重要的
    • 恶意的意图有人能写出一类叫做 java.lang.Object,可用于
      访问任何在硬盘上的目录。 因为 JVM 的信任 java.lang.Object 类,它不会关注这方面的活动。因此,如果自定义 java.lang.Object 被允许加载,安全管理器将很容易瘫痪。幸运的是,这将不会发生,因为委派模型会阻止这种情况的发生。

    当自定义 java.lang.Object 类在程序中被调用的时候, system 类加载器将该请求委派给 extension 类加载器,然后委派给 bootstrap 类加载器。这样 bootstrap类加载器先搜索的核心库,找到标准 java.lang.Object 并实例化它。这样,自定义 java.lang.Object 类永远不会被加载。

    双亲委派模型的实现,会先往上找父类加载器加载类,当所有父类加载器都无法加载的时候,最后再调用自己的findClass方法加载。

        protected Class<?> loadClass(String name, boolean resolve)
            throws ClassNotFoundException
        {
            synchronized (getClassLoadingLock(name)) {
                // First, check if the class has already been loaded
                Class<?> c = findLoadedClass(name);
                if (c == null) {
                    long t0 = System.nanoTime();
                    try {
                        if (parent != null) {
                            c = parent.loadClass(name, false);
                        } else {
                            c = findBootstrapClassOrNull(name);
                        }
                    } catch (ClassNotFoundException e) {
                        // ClassNotFoundException thrown if class not found
                        // from the non-null parent class loader
                    }
    
                    if (c == null) {
                        // If still not found, then invoke findClass in order
                        // to find the class.
                        long t1 = System.nanoTime();
                        c = findClass(name);
    
                        // this is the defining class loader; record the stats
                        sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                        sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                        sun.misc.PerfCounter.getFindClasses().increment();
                    }
                }
                if (resolve) {
                    resolveClass(c);
                }
                return c;
            }
        }
    
    

    自定义类加载器

    对于java.lang.ClassLoader的loadClass(String name, boolean resolve)方法的解析来看,可以得出以下2个结论:

    1. 如果不想打破双亲委派模型,那么只需要重写findClass方法即可
    2. 如果想打破双亲委派模型,那么就重写整个loadClass方法

    demo

    这是在非classpath路径下的Sample.class,只有自定义的类加载器才能加载。这里lib2,和lib3,见第四幅图


    .class .java classpath

    xyy.test.classloader.load.ClassLoaderTree#testClass2方法的结构。理解双亲委派模型很有帮助。class4的parent 设为null 则为Bootstrap ClassLoader。默认都是Application ClassLoader


    xyy.test.classloader.load.ClassLoaderTree#testClass2

    输出:

    class4: java.lang.NullPointerException
    class1’ClassLoader:fscl1
    class2’ClassLoader:fscl1
    class3’ClassLoader:sun.misc.Launcher$AppClassLoader@5305068a
    class4’ClassLoader:null
    

    如果把Sample.java删除,那么也就是classpath目录下的Sample.class没了,那么class3’ClassLoader 也将没有,y一直找到根加载器也无法加载。

    ps: 下面这点非常重要,也就是说lib1下面不能直接放Sample.class 需要前缀相同。

            // 前缀必须与类的package的路径一致,否则会报NoClassDefFoundError
            String className = "xyy.test.classloader.load.Sample";
    
    package xyy.test.classloader.load;
    
    /**
     * Created by xyy on 16-8-17.
     */
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class FileSystemClassLoader extends ClassLoader {
    
        private String loaderName="FileSystemClassLoader";
        private String  rootDir;
        private boolean localFirst=true;
    
        public FileSystemClassLoader(boolean localFirst, String rootDir) {
            this.rootDir = rootDir;
            this.localFirst = localFirst;
        }
        public FileSystemClassLoader(String rootDir,String loaderName) {
            super();
            this.rootDir = rootDir;
            this.loaderName=loaderName;
        }
        public FileSystemClassLoader(ClassLoader parent,String rootDir,String loaderName) {
            super(parent);
            this.rootDir = rootDir;
            this.loaderName=loaderName;
        }
    
        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if (localFirst) {
                /**
                 * 找不到时,用父类的loadClass
                 */
                Class clazz = findClass(name);
                if (clazz != null) {
                    return clazz;
                }
    
                return super.loadClass(name);
            } else {
                return super.loadClass(name);
            }
        }
    
        protected Class<?> findClass(String name) {
            byte[] classData = getClassData(name);
            if (classData == null) {
                return null;
            } else {
                return defineClass(name, classData, 0, classData.length);
            }
        }
    
        private byte[] getClassData(String className) {
            String path = classNameToPath(className);
            try {
                System.out.println(path);
                InputStream ins = new FileInputStream(path);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int bufferSize = 4096;
                byte[] buffer = new byte[bufferSize];
                int bytesNumRead = 0;
                while ((bytesNumRead = ins.read(buffer)) != -1) {
                    baos.write(buffer, 0, bytesNumRead);
                }
                return baos.toByteArray();
            } catch (IOException e) {
               // e.printStackTrace();
                // 这里由于如果本次找不到是会报异常的,所以catch掉,然后往上找classloader
                System.out.println("in getClassData error: "+className);
            }
            return null;
        }
    
        private String classNameToPath(String className) {
            return rootDir + File.separatorChar + className.replace('.', File.separatorChar) + ".class";
        }
    
        @Override
        public String toString() {
            return loaderName;
        }
    }
    
    
    package xyy.test.classloader.load;
    
    import java.lang.reflect.Method;
    
    /**
     * Created by xyy on 16-8-17.
     */
    public class ClassLoaderTree {
    
        private static String user_dir = System.getProperty("user.dir");
    
        public static void main(String[] args) {
            // testAll();
            testClassLoader1();
            // testClassLoader2();
        }
    
        public static void testClassLoader1() {
    
            String classDataRootPath = user_dir + "/target/test-classes";
            String classDataRootPath2 = user_dir + "/myApp/lib1";
            FileSystemClassLoader fscl1 = new FileSystemClassLoader(true, classDataRootPath);
            FileSystemClassLoader fscl2 = new FileSystemClassLoader(true, classDataRootPath);
            FileSystemClassLoader fscl3 = new FileSystemClassLoader(true, classDataRootPath2);
            boolean ret = (fscl1.equals(fscl2));
    
            // 前缀必须与类的package的路径一致,否则会报NoClassDefFoundError
            String className = "xyy.test.classloader.load.Sample";
            try {
                Class<?> class1 = fscl1.loadClass(className);
                Object obj1 = class1.newInstance();
                Object obj1_1 = class1.newInstance();
                Class<?> class2 = fscl2.loadClass(className);
                Object obj2 = class2.newInstance();
                Class<?> class3 = fscl3.loadClass(className);
                Object obj3 = class3.newInstance();
    
                // Sample 和 obj1所用的类加载器不一样
                System.out.println("class1:" + class1.getClassLoader());
                System.out.println("class2:" + class2.getClassLoader());
                System.out.println("class3:" + class3.getClassLoader());
                System.out.println("Sample.class" + Sample.class.getClassLoader());
    
                // 两个不同的Sample的不同的toString,你可以先编译两份不一样的Sample类。
                System.out.println(obj1.toString());
                System.out.println(obj3.toString());
    
                // 不同类加载器加载的类,是不同相互强转的
                System.out.println("------test  cast-------------");
                try {
                    Sample sample = (Sample) obj1;
                } catch (Exception e) {
                    System.err.println(e);
                }
    
                System.out.println("--------invoke method -----------");
                try {
                    // obj1=(Sample)obj2;
                    Method method = class1.getMethod("setSample", java.lang.Object.class);
                    // will be error
                    // method.invoke(obj1, obj2);
                    // 正确
                    method.invoke(obj1, obj1_1);
                } catch (Exception e) {
                    // e.printStackTrace();
                    System.err.println(e);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void testClassLoader2() {
            String lib1 = user_dir + "/myApp/lib1";
            String lib2 = user_dir + "/myApp/lib2";
            String lib3 = user_dir + "/myApp/lib3";
            FileSystemClassLoader fscl1 = new FileSystemClassLoader(lib1, "fscl1");
            FileSystemClassLoader fscl2 = new FileSystemClassLoader(fscl1, lib2, "fscl2");
            FileSystemClassLoader fscl3 = new FileSystemClassLoader(lib3, "fscl3");
            FileSystemClassLoader fscl4 = new FileSystemClassLoader(null, lib3, "fscl4");
            String className = "xyy.test.classloader.load.Sample";
            try {
                Class<?> class1 = fscl1.loadClass(className);
                class1.newInstance();
    
                Class<?> class2 = fscl2.loadClass(className);
                class2.newInstance();
    
                Class<?> class3 = fscl3.loadClass(className);
                class3.newInstance();
    
                Class<?> class4 = null;
                try {
                    class4 = fscl4.loadClass(className);
                    class4.newInstance();
                } catch (Exception e) {
                    System.err.println("class4: " + e);
                }
    
                System.out.println("class1’ClassLoader:" + class1.getClassLoader());
                System.out.println("class2’ClassLoader:" + class2.getClassLoader());
                System.out.println("class3’ClassLoader:" + class3.getClassLoader());
                System.out.println("class4’ClassLoader:" + (class4 == null ? null : class4.getClassLoader()));
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        private static void testAll() {
            ClassLoader loader = ClassLoaderTree.class.getClassLoader();
            while (loader != null) {
                System.out.println(loader.toString());
                loader = loader.getParent();
            }
        }
    }
    
    package xyy.test.classloader.load;
    
    /**
     * Created by xyy on 16-8-17.
     */
    public class Sample {
        private Sample instance;
    
        public void setSample(Object instance) {
            this.instance = (Sample) instance;
        }
    
        public String toString(){
            return "Sample str1";
        }
    }
    
    

    相关文章

      网友评论

        本文标题:类加载器

        本文链接:https://www.haomeiwen.com/subject/xtinbttx.html