自定义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

(全文完)

(转载本站文章请注明作者和出处 自定义ClassLoader