天天看點

類加載原理及自定義類加載器

參考文檔: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