类加载原理及自定义类加载器

来源:互联网 发布:未设置为接受端口1080 编辑:程序博客网 时间:2024/04/27 18:25

参考文档:a。《理解java类加载原理》b。《揭示java类加载内幕》

一 初识类加载器

     java虚拟机通过‘类加载器’来加载类到内存中,即class文件。类加载器相关的类是ClassLoader,这是一个抽象类。java程序的每个类都有一个指向ClassLoader的引用,可以通过getClassLoaer()来知道。

    当一个类要被加载时,系统按如下顺序搜寻该类及其相关的类(来自understanding extenion class loading):

首先是自定义类,然后是系统默认的一些类

1 Bootstrap classes  the runtime classes in rt.jar and internationolazation i18n.jar

2 Installed extensions classes in the jar fileslib/ext directory of the jre

3 The class path classes,including classes in JAR files,on paths specified by th e system property java.class.path. If a JAR file on the classpath has a manifest with the Class-Path attribute,JAR files specified by the Class-Path attribute will be Searched also.By default,the java.class.path property's value is.,thecurrent directory.You can change the  value by setting the CLASSPATH enviroment variable or by using th -classpaht or -cp command-line options.These command-line options override the setting of the CLASSPATH environment variable.Note that in te Java1.2 software,java.class.path no longer includes the bootstrap classes in rt.jar and i18n.jar

(这样word by word的输入,好不爽,有没有什么办法呢?)

《understanding extension classloading》一文中还提到了一些ClassLoader,如java.net.URLClassLoader等,这些类都是ClassLoader的子类,可直接调用它们)

 

二 自定义类加载器

    开发者可通过自定义类加载器来控制JVM中的类加载行为,比如,从网络加载(显式加载):

ClassLoader loader=new NetWorkClassLoader(host,port);

Object main=loader.loadClass("main",true).newInstance();

在安全性,加密等方面也很有用处。在a文中有提到。

顺便提一下显式加载(见上文)与隐式加载(下文):

ClassLoad loader=getSomeLoader();

Object main=loader.loadClass("main",true).newInstance();

 

自定义类就是对ClassLoader继承,我现在还不想深究自定义加载类的写法,可以参考a文,b文写的很罗嗦,要有耐心看,我还没有完全看懂。

自定义加载类写好后,就可以这样执行:

java MyClassLoader xxxx

原创粉丝点击