双亲委派

ClassLoader类中负责根据类的完整路径加载class的过程

 

/*
 * @param name 类的完整路径 
 */
protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
        // 同步代码块,避免多个线程同时加载类。
        synchronized (getClassLoadingLock(name)) {
            // 首先要在方法区查找name的类是否已经被加载了
            Class<?> c = findLoadedClass(name);
            // 方法区中还没有name对应的类
            if (c == null) {
                long t0 = System.nanoTime();
                try {
                    // 通过父类加载器加载name的类
                    if (parent != null) { //不考虑自定义类加载器,则parent为extClassLoader
                        c = parent.loadClass(name, false); // 递归查找
                    } else {
                        // 当前的类加载器是extClassLoader
                        // 因此需要从extClassLoader的父类加载器BootstrapClassLoader
                        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;
        }
    }

 

posted @ 2022-09-22 14:23  岁月记忆  阅读(23)  评论(0)    收藏  举报