java类加载器

来源:互联网 发布:淘宝店全包 编辑:程序博客网 时间:2024/05/17 00:10

启动类加载器 bootstrap classloader 加载%JAVA_HOME%/jre/lib/下的JAVA平台自身的类

扩展类加载器 extension classsloader 用于加载%JAVA_HOME%/jre/lib/ext/下的类,它的实现类是sun.misc.Launcher$ExtClassLoader,是一个内部类

系统类加载器 system classloader是jvm启动时,根据classpath参数创建的类加载器


几个方法

1. ClassLoader.getSystemClassLoader()得到的是系统类加载器

2. Class.getClassLoader()得到的是加载这个类的加载器

public class TestClass {//    private int m;//    public int inc(int m) {//        return m+1;//    }    public static void main(String[] args) {        System.out.println(TestClass.class.getClassLoader());    }}
输出

sun.misc.Launcher$AppClassLoader@26b418

3.

Thread.currentThread().getContextClassLoader()
得到是当前线程相关的类加载器,每一个线程都相关联一个类加载器,子线程继承了父线程的加载器,如果没有设置,那就是系统类加载器。


4.class.forname("XXX")

如果对象A使用class.forname方法没有传递一个classloader,那么会使用加载A类的类加载器。


双亲委派机制

先让父加载器加载类,不行在自己。

ClassLoader抽象类的几个方法

1.

loadClass
双亲委派机制的体现

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;    }}
先用父加载器parent加载。。。不行再用findClass()自己加载findClass由子类实现。。。比如urlclassloader实现了findclass方法,然后又调用了defineclass方法

defineclass()方法创建类对象,将字节流解析成JVM能够识别的Class对象。


resolveClass

连接过程


参考

http://kyfxbl.iteye.com/blog/1900855

http://blog.csdn.net/vking_wang/article/details/17162327

http://daizuan.iteye.com/blog/1097105


0 0
原创粉丝点击