自定义ClassLoader

原文

https://www.toocruel.net/my-classloader/

MyCl.java 自定义的ClassLoader类

import java.io.*;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/9/13 下午6:07
 */
public class MyCl extends ClassLoader {
    private String path;   //类的加载路径
    private String name;   //类加载器的名字

    public MyCl() {}
    public MyCl(String path, String name){
        this.path = path;
        this.name = name;
    }


    //用于寻找类文件
    public Class findClass(String name) {
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }

    //用于加载类文件
    private byte[] loadClassData(String name) {
        name = name.replaceAll("\\.","/");
        name = path + name + ".class";
        //使用输入流读取类文件
        InputStream in = null;
        //使用byteArrayOutputStream保存类文件。然后转化为byte数组
        ByteArrayOutputStream out = null;
        try {
            in = new FileInputStream(new File(name));
            out = new ByteArrayOutputStream();
            int i = 0;
            while ( (i = in.read()) != -1){
                out.write(i);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return out.toByteArray();

    }

    public String getName() {
        return name;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

测试

准备要加载的class文件

QQ20180914-100330

执行main方法测试
/**
 * @Description
 * @Auther sty
 * @createTime 2018/9/13 上午11:42
 */
public class Test {
    public static void main(String[] args) {
        MyCl cl = new MyCl("/Users/sty/Downloads/untitled/","mycl");

        Class ha = cl.findClass("net.toocruel.test.Ha");

        System.out.println(ha.getClassLoader());

    }
}

结果

QQ20180914-100126

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值