ClassLoader中的loadClass和findClass方法
阅读原文时间:2021年04月20日阅读:1

Java中ClassLoader的具体实现

Java虚拟机的类加载器本身可以满足加载的要求,但是也允许开发者自定义类加载器。

jdk中classloader中loadclass方法的实现如下所示:

protected Class<?> loadClass(String name, boolean resolve)
        throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            //查找.class是否被加载过
            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();
                }
            }
            // 解析class文件,就是将符号引用替换为直接引用的过程
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }

在这其中,涉及到一个findclass方法,查看源码后结果如下所示:

protected Class<?> findClass(String name) throws ClassNotFoundException {
        throw new ClassNotFoundException(name);
    }

这只是一个空方法,返回内容为class,方法其中没有任何内容,只抛出了个异常,说明这个方法需要开发者自己去实现。

自定义类加载器

首先根据源码可以知道,如果自定义的方法不想违背双亲委派模型,则只需要重写findclass方法即可,如果想违背双亲委派模型,则还需要重写loadclass方法。