自定義ClassLoader測試

自定義ClassLoader直接繼承ClassLoader抽象類, 覆寫

protected Class<?> findClass(String name) throws ClassNotFoundException

方法, 實(shí)現(xiàn)自定義加載類. 在 #ClassLoader抽象類中, 給出了 class實(shí)例化方法:

protected final Class<?> defineClass(byte[] b, int off, int len)

這個(gè)方法目的是將 class字節(jié)流轉(zhuǎn)為 class instance

/**
* Converts an array of bytes into an instance of class <tt>Class</tt>.
* Before the <tt>Class</tt> can be used it must be resolved.
*
* <p> This method assigns a default {@link java.security.ProtectionDomain
* <tt>ProtectionDomain</tt>} to the newly defined class.  The
* <tt>ProtectionDomain</tt> is effectively granted the same set of
* permissions returned when {@link
* java.security.Policy#getPermissions(java.security.CodeSource)
* <tt>Policy.getPolicy().getPermissions(new CodeSource(null, null))</tt>}
* is invoked.  The default domain is created on the first invocation of
* {@link #defineClass(String, byte[], int, int) <tt>defineClass</tt>},
* and re-used on subsequent invocations.
*
* <p> To assign a specific <tt>ProtectionDomain</tt> to the class, use
* the {@link #defineClass(String, byte[], int, int,
* java.security.ProtectionDomain) <tt>defineClass</tt>} method that takes a
* <tt>ProtectionDomain</tt> as one of its arguments.  </p>
*
* @param  name
*        The expected <a href="#name">binary name</a> of the class, or
*        <tt>null</tt> if not known
*
* @param  b
*        The bytes that make up the class data.  The bytes in positions
*        <tt>off</tt> through <tt>off+len-1</tt> should have the format
*        of a valid class file as defined by
*        <cite>The Java&trade; Virtual Machine Specification</cite>.
*
* @param  off
*        The start offset in <tt>b</tt> of the class data
*
* @param  len
*        The length of the class data
*
* @return  The <tt>Class</tt> object that was created from the specified
*          class data.
*
* @throws  ClassFormatError
*          If the data did not contain a valid class
*
* @throws  IndexOutOfBoundsException
*          If either <tt>off</tt> or <tt>len</tt> is negative, or if
*          <tt>off+len</tt> is greater than <tt>b.length</tt>.
*
* @throws  SecurityException
*          If an attempt is made to add this class to a package that
*          contains classes that were signed by a different set of
*          certificates than this class (which is unsigned), or if
*          <tt>name</tt> begins with "<tt>java.</tt>".
*
* @see  #loadClass(String, boolean)
* @see  #resolveClass(Class)
* @see  java.security.CodeSource
* @see  java.security.SecureClassLoader
*
* @since  1.1
*/
protected final Class<?> defineClass(String name, byte[] b, int off, int len)
    throws ClassFormatError
{
    return defineClass(name, b, off, len, null);
}

這里是從本地文件系統(tǒng)中通過文件的方式讀取*.class文件, 將獲取到的全部class文件字節(jié)流傳遞給 #defineClass方法, 實(shí)例化. 這之后我們就可以使用這個(gè)類對象了.

public class MyClassLoader extends ClassLoader {

    private String dir ;

    public MyClassLoader(String dir) {
        //
        this.dir = dir ;
    }

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        //

        if (StringUtils.isBlank(name))
            throw new ClassNotFoundException() ;

        String path = this.getPath(name) ;

        byte[] ret = this.getClassData(path) ;
        if (ret == null)
            throw new ClassNotFoundException("讀取".concat(path).concat("失敗.")) ;

        return defineClass(name, ret,0, ret.length) ;
    }

    private byte[] getClassData(String path) {
        System.out.println("Path: - ".concat(path));
        try {
            InputStream inputStream = new FileInputStream(new File(path)) ;
            ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
            byte[] buffer = new byte[1024] ;
            while (inputStream.read(buffer) != -1) {
//                baos.write(buffer);
                baos.write(buffer, 0, buffer.length);
            }

            return baos.toByteArray() ;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null ;
    }

    private String getPath(String className) {

        return this.dir.concat(className.replace(".", File.separator)).concat(".class") ;
    }
}

隨便定一個(gè)使用自定義類加載器加載的類:

public class ABean {

    public ABean() {
        System.out.println("初始化ABean.");
    }

    @Override
    public String toString() {
        return "hello, myClassLoader...." ;
    }
}

測試類:

public static void main(String[] args) {
        //JVM-classLoader test
        String dir = "/test/target/classess/test/jvm/",
        clsName = "test.jvm.ABean" ;

        MyClassLoader myClassLoader = new MyClassLoader(dir) ;
        try {
            Class cls = myClassLoader.loadClass(clsName) ;
            System.out.println(cls.newInstance().toString()) ;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//輸出

初始化ABean.
hello, myClassLoader....

注意
需要注意的是

protected final Class<?> defineClass(String name, byte[] b, int off, int len)

這個(gè)方法第一個(gè)參數(shù)是指: 類全名[Full-className] 否則會(huì)有異常: java.lang.NoClassDefFoundError 這里我根據(jù)方法文檔, 大概是因?yàn)?

* @throws  NoClassDefFoundError
*          If <tt>name</tt> is not equal to the <a href="#name">binary
*          name</a> of the class specified by <tt>b</tt>

在讀取class文件得到的byteStream名稱為 test/jvm/ABean/class 但是傳遞給#defineClass方法的名稱卻是 ABean.

以上代碼測試環(huán)境為

Linux arch 4.14.10-1-ARCH x86_64 GNU/Linux
觸發(fā)類加載有以下三種方式:
  • 命令行啟動(dòng)應(yīng)用時(shí)候由JVM初始化加載
  • 通過Class.forName()方法動(dòng)態(tài)加載
  • 通過ClassLoader.loadClass()方法動(dòng)態(tài)加載
類裝載器把一個(gè)類裝入JVM中逗抑,要經(jīng)過以下步驟:
 - 裝載:查找和導(dǎo)入Class文件;
 - 鏈接:把類的二進(jìn)制數(shù)據(jù)合并到JRE中峦树; 這個(gè)過程包括三個(gè)步驟:
      - 校驗(yàn):檢查載入Class文件數(shù)據(jù)的正確性;
      - 準(zhǔn)備:給類的靜態(tài)變量分配存儲(chǔ)空間君账;
      - 解析:將符號引用轉(zhuǎn)成直接引用座柱;
 - 初始化:對類的靜態(tài)變量焕梅,靜態(tài)代碼塊執(zhí)行初始化操作
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市担孔,隨后出現(xiàn)的幾起案子江锨,更是在濱河造成了極大的恐慌,老刑警劉巖糕篇,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件泳桦,死亡現(xiàn)場離奇詭異,居然都是意外死亡娩缰,警方通過查閱死者的電腦和手機(jī)灸撰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來拼坎,“玉大人浮毯,你說我怎么就攤上這事√┘Γ” “怎么了债蓝?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長盛龄。 經(jīng)常有香客問我饰迹,道長,這世上最難降的妖魔是什么余舶? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任啊鸭,我火速辦了婚禮,結(jié)果婚禮上匿值,老公的妹妹穿的比我還像新娘赠制。我一直安慰自己,他們只是感情好挟憔,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布钟些。 她就那樣靜靜地躺著,像睡著了一般绊谭。 火紅的嫁衣襯著肌膚如雪政恍。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天达传,我揣著相機(jī)與錄音篙耗,去河邊找鬼迫筑。 笑死,一個(gè)胖子當(dāng)著我的面吹牛鹤树,可吹牛的內(nèi)容都是我干的铣焊。 我是一名探鬼主播逊朽,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼罕伯,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了叽讳?” 一聲冷哼從身側(cè)響起追他,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎岛蚤,沒想到半個(gè)月后邑狸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡涤妒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年单雾,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片她紫。...
    茶點(diǎn)故事閱讀 39,785評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡硅堆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出贿讹,到底是詐尸還是另有隱情渐逃,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布民褂,位于F島的核電站茄菊,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏赊堪。R本人自食惡果不足惜面殖,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望哭廉。 院中可真熱鬧畜普,春花似錦、人聲如沸群叶。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽街立。三九已至舶衬,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間赎离,已是汗流浹背逛犹。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人虽画。 一個(gè)月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓舞蔽,卻偏偏與公主長得像,于是被迫代替她去往敵國和親码撰。 傳聞我的和親對象是個(gè)殘疾皇子渗柿,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容