简单的自定义类加载器

package com.java.basic.classloaders;

import java.io.*;

public class FileSystemClassLoader extends ClassLoader{

    private String dirPath;

    public FileSystemClassLoader(String dirPath) {
        this.dirPath = dirPath;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        /**
         * 1. 先获取是否已经被加载
         * 2. 无
         *  1. 使用双亲委托机制
         *  2. 失败
         *   1. 自己加载
         */
        Class targetC = null;
        targetC = findLoadedClass(name);
        if (targetC != null) return targetC;
        try {
            targetC = getParent().loadClass(name);
        } catch (ClassNotFoundException e) {
        }
        if (targetC == null) {
            try {
                byte[] bytes = dataBytes(name);
                targetC = defineClass(name, bytes, 0, bytes.length);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return targetC;
    }

    private byte[] dataBytes(String name) throws IOException {
        String path = dirPath + "/" + name.replaceAll("\\.", "/") + ".class";
        // 获取该文件的流, 并获取其字节码数组数据
        InputStream in = new FileInputStream(path);
        ByteArrayOutputStream byteIn = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int code = 0;
        while ((code = in.read(bytes)) != -1) {
            byteIn.write(bytes, 0 , code);
        }
        return byteIn.toByteArray();
    }
}

package com.java.basic.classloaders;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class LoaderTest {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {

        FileSystemClassLoader loader = new FileSystemClassLoader("D:/new~dir");
        Class Hello = loader.loadClass("com.java.basic.Hello");
        System.out.println(Hello);
        Method main = Hello.getMethod("main", String[].class);
        // 此处需要将其强转为一个对象. 否则会被认为是多个参数
        main.invoke(Hello.newInstance(),  (Object) new String[]{"a","b"});
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43503284/article/details/85934038