Dissect Eclipse Plugin Framework (3)

了解Eclipse的Plugin Framework需要对ClassLoader(类装载器)有比较深入的了解,建议读读JDK的源代码,会很有帮助。

ClassLoader - 顾名思义,就是Java中用来装载类的部分,要将一个类的名字装载为JVM中实际的二进制类数据。在JVM中,任何一个类被加载,都是通过ClassLoader来实现的,同时,每个Class对象也都有一个引用指向装载他的ClassLoader,你可以通过getClassLoader()方法得到它。

ClassLoader只是一个抽象类,你可以定义自己的ClassLoader来实现特定的Load的功能。Eclipse Plugin Framework就实现了自己的ClassLoader。

ClassLoader使用所谓的"Delegation Model"(“双亲委托模型”)来查找、定位类资源,每一个ClassLoader都有自己一个父ClassLoader实例,当这个ClassLoader被要求加载一个类时,它首先会询问自己的父ClassLoader,看看他是否能加载,如果不能的话,才自己加载。

Java ClassLoader的体系结构是

Bootstrap ClassLoader <- Standard Extensions ClassLoader <- Class Path Class Loader

最后来看一下代码:

  1. protected synchronized Class<?> loadClass(String name, boolean resolve)
  2.     throws ClassNotFoundException
  3.     {
  4.     // First, check if the class has already been loaded
  5.     Class c = findLoadedClass(name);
  6.     if (c == null) {
  7.         try {
  8.         if (parent != null) {
  9.             c = parent.loadClass(name, false);
  10.         } else {
  11.             c = findBootstrapClass0(name);
  12.         }
  13.         } catch (ClassNotFoundException e) {
  14.             // If still not found, then invoke findClass in order
  15.             // to find the class.
  16.             c = findClass(name);
  17.         }
  18.     }
  19.     if (resolve) {
  20.         resolveClass(c);
  21.     }
  22.     return c;
  23. }

可见,ClassLoader首先会查找该类是否已经被装载,如果没有,就询问自己的父ClassLoader,如果还不能装载,就调用findClass()方法来装载类。所以,一般简单的自定义ClassLoader只需要重写findClass方法就可以了。

如果你的类不是文件,比如说是序列化在数据库中的二进制流或者网络上的Bit流,就需要重写defineClass()方法,来将二进制数据映射到运行时的数据结构。另外一种需求也可能是你需要对类文件进行某种操作(比如按位取反?),也需要定义自己的defineClass()方法。

还需要注意的是资源的加载和系统Native库的加载,这个可以留在以后再作讨论。

Popularity: 24%

Related entries:

Leave a comment

(required)

(required)


Information for comment users
Line and paragraph breaks are implemented automatically. Your e-mail address is never displayed. Please consider what you're posting.

Use the buttons below to customise your comment.


RSS feed for comments on this post | TrackBack URI

 

Creative Commons License
This work is licensed under a Creative Commons License.

我只有两天,我没有把握,一天用来出生,一天用来死亡