JVM(九) 类加载的父亲委托机制

父子关系

从JDK1.2版本开始,类的加载过程采用父亲委托机制,这种机制能更好地保证Java平台的安全。在此委托机制中,各个加载器按照父子关系形成了树形结构,除了根类加载器外, 其余的类加载器都有且只有一个父加载器。


比如:

Class sampleClass = loader2.loadClass("Sample");

根据上图进行分析:

loader2首先从自己的命名空间中查找Sample类是否已经被加载,如果已经加载,就直接返回代表Sample类的Class对象的引用。

如果Sample类还没有被加载,loader2首先请求loader1代为加载,loader1再请求系统类加载器代为加载器,系统类加载器再请求扩展类加载器代为加载,扩展类加载器再请求根类加载器进行加载,若能加载成功,则将Sample类所对应的Calss对象的引用返回给loader1,loader1再将引用返回给loader2,从而成功将Sample类加载进虚拟机。若系统类加载器不能加载Sample类,则loader1尝试加载Sample类,若loader1也不能成功加载,则loader2尝试加载。若所有的父加载器及loader2本身都不能加载,则抛出ClassNotFoundException异常。

所有一个类加载器能成功加载Sample类,那么这个类加载器被称为定义类加载器,所有能成功返回Class对象的引用的类加载器(包括定义类加载器)都被称为初始类加载器

假设loader1实际加载了Sample类,则loader1为Sample类的定义类加载器,loader2和loader1为Sample类的初始类加载器。

需要指出的是,加载器之间的父子关系实际上指的是加载器对象之间的包装关系,而不是类之间的继承关系。一对父子加载器可能是同一个加载器类的两个实例,也可能不是。在子加载器对象中包装了一个父加载器对象。

例如以下loader1和loader2都是MyClassLoader类的实例,并且loader2包装了loader1,loader1是loader2的父加载器。

ClassLoader loader1 = new MyClassLoader();

//参数loader1将作为loader2的父加载器

ClassLoader loader2 = new MyClassLoader(loader1);

我们可以来看看官方文档上的ClassLoader的构造方法:

http://docs.oracle.com/javase/7/docs/api/

  • ClassLoader
    protected ClassLoader(ClassLoader parent)
    Creates a new class loader using the specified parent class loader for delegation.

    If there is a security manager, its checkCreateClassLoader method is invoked. This may result in a security exception.

    Parameters:
    parent - The parent class loader
    Throws:
    SecurityException - If a security manager exists and its checkCreateClassLoader method doesn't allow creation of a new class loader.
    Since:
    1.2
  • ClassLoader
    protected ClassLoader()
    Creates a new class loader using the ClassLoader returned by the method getSystemClassLoader() as the parent class loader.

    If there is a security manager, its checkCreateClassLoader method is invoked. This may result in a security exception.

    Throws:
    SecurityException - If a security manager exists and its checkCreateClassLoader method doesn't allow creation of a new class loader.

可以看到一个是有参数的,一个是没有参数的。有参数的是指定了它的父加载器。没有参数的是用getSystemClassLoader方法生成一个系统类加载器,做为你自定义的类加载器的父加载器。

优点

父亲委托机制的优点是能够提高软件系统的安全性。因为在此机制下,用户自定义的类加载器不可能加载应该由父加载器加载的可靠类,从而防止不可靠甚至恶意的代码代替由父加载器加载的可靠代码。例如:java.lang.Object类总是由根类加载器加载,其他任何用户自定义的类加载器都不可能加载含有恶意代码的java.lang.Object类。


评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值