ClassLoader中的几个重要方法

1.loadClass(String name)

①具体源码:

public Class loadClass(String name) throws ClassNotFoundException {
        return loadClass(name, false);
    }

②分析:

期间调用loadClass(name, false)方法

2.loadClass(name, false)

①具体源码:

protected Class loadClass(String name, boolean resolve)
            throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) {
            //首先,检查类文件是否已经被加载过
            Class c = findLoadedClass(name);
            //类文件未被加载过
            if (c == null) {
                //设定加载时间起始点
                long t0 = System.nanoTime();
                try {
                    //其父加载器不为空,说明父加载器为引导加载器
                    if (parent != null) {
                        //通过父加载器搜索name指定的类文件
                        c = parent.loadClass(name, false);
                    } else {
                        //父加载器为空,说明父加载器为启动加载器搜索类文件
                        //启用bootstrap class loader
                        c = findBootstrapClassOrNull(name);
                    }
                } catch (ClassNotFoundException e) {
                    //如果非空父加载器中找不到name指定的类文件
                    //抛出ClassNotFoundException异常
                }
                //父加载器或者启动加载器中都未搜索到该类文件
                if (c == null) {
                   //设定加载时间结点
                    long t1 = System.nanoTime();
                    //当前加载器内搜索name指定的类文件
                    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();
                }
            }
            //resolve为true时处理类文件
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }

3.findClass(String name)

①ClassLoader中定义的findClass()

public Class loadClass(String name) throws ClassNotFoundException {
        return loadClass(name, false);
    }

②网络类加载器子类实现实例:

class NetworkClassLoader extends ClassLoader {
         String host;
         int port;

         public Class findClass(String name) {
             byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         }

         private byte[] loadClassData(String name) {
             // load the class data from the connection
              . . .
         }
     }

4.defineClass(byte[] b, int off, int len)

①ClassLoader中定义的defineClass()

@Deprecated
    protected final Class defineClass(byte[] b, int off, int len)
        throws ClassFormatError
    {
        return defineClass(null, b, off, len, null);
    }

②描述:

将一个字节数组转为Class对象,这个字节数组是class文件读取后最终的字节数组

如果class文件是加密过的则需要解密后作为参数传入defineClass中

你可能感兴趣的:(Java)