溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

一個(gè)基本的自定義類加載器

發(fā)布時(shí)間:2020-07-06 20:09:32 來源:網(wǎng)絡(luò) 閱讀:679 作者:xpleaf 欄目:編程語言

實(shí)現(xiàn)自定義類加載器的三步:

  • 1.繼承ClassLoader
  • 2.重寫findClass()方法
  • 3.調(diào)用defineClass()方法

一個(gè)基本的自定義類加載器代碼如下:

package cn.xpleaf.coding.c4;

import java.io.*;

/**
 * @author xpleaf
 * @date 2019/3/10 11:10 AM
 */
public class CustomClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] result = getClassFromCustomPath(name);
            if (result == null) {
                throw new FileNotFoundException(name);
            } else {
                // defineClass方法將字節(jié)碼轉(zhuǎn)化為類
                return defineClass(name, result, 0, result.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ClassNotFoundException(name);
    }

    private byte[] getClassFromCustomPath(String name) {
        // 從自定義路徑中加載指定類,返回類的字節(jié)碼文件
        InputStream in = null;
        ByteArrayOutputStream out = null;
        String path = "/Users/yeyonghao/" + name + ".class";
        try {
            in = new FileInputStream(path);
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            return out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        CustomClassLoader customClassLoader = new CustomClassLoader();
        try {
            Class<?> clazz = Class.forName("One", true, customClassLoader);
            Object obj = clazz.newInstance();
            // cn.xpleaf.coding.c4.CustomClassLoader@610455d6
            System.out.println(obj.getClass().getClassLoader());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

執(zhí)行結(jié)果如下:

cn.xpleaf.coding.c4.CustomClassLoader@610455d6
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI