自定义类加载器

自定义类加载器,破坏双亲委派机制 

可以选择继承classLoader或者URLClassLoader

package com.example.demo;

import lombok.SneakyThrows;

import java.io.*;

/**
 * @author dh
 */
public class UserDefineClassLoader extends ClassLoader{

    private String rootPath;

    public UserDefineClassLoader( String rootPath) {
        this.rootPath = rootPath;
    }

    @SneakyThrows
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        //转换为以文件路径表示的文件
        String path = classTofileName(name);

        //获取指定路径的class文件的二进制流数据
        byte[] data = getbyteFromPath(path);

        //自定义ClassLoader 内部调用defineClass
        return defineClass(name,data,0,data.length);
    }

    private byte[] getbyteFromPath(String filePath) throws IOException {
        FileInputStream stream = null;
        ByteArrayOutputStream baos = null;
        try {
            stream = new FileInputStream(filePath);
             baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = stream.read()) != -1){
                baos.write(buffer,0,len);
            }
            return baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            stream.close();
            baos.close();
        }
    }

    private String classTofileName(String name) {

        return rootPath+"\\"+name.replace(".","\\");
    }


}

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值