其他分享
首页 > 其他分享> > 自定义加载类

自定义加载类

作者:互联网

public class UserDefineClassLoader extends ClassLoader{

    private String rootPath;

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

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        //转换为以文件路径表示的文件
        String filePath = classToFilePath(name);

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

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

    private byte[] getByteFromPath(String filePath) {

        FileInputStream stream = null;
        ByteArrayOutputStream outputStream = null;

        try {
            stream = new FileInputStream(filePath);

            outputStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len;

            while ((len = stream.read(buffer)) != -1){
                outputStream.write(buffer,0,len);
            }

            return outputStream.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (stream != null){
                    stream.close();
                }
                if (outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private String classToFilePath(String name) {
        return rootPath+"\\"+name.replace(".","\\")+".class";
    }

    public static void main(String[] args) {
        //                                                                     E:\code\java-learn\demo\src
        UserDefineClassLoader classLoader = new UserDefineClassLoader("E:\\code\\java-learn\\demo\\target\\classes");

        try {
            Class<?> aClass = classLoader.findClass("com.feng.demo.leetCode.ListDemo");
            System.out.println(aClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

注意:

new UserDefineClassLoader()放的是class文件所在的位置

标签:outputStream,String,stream,UserDefineClassLoader,加载,new,null,自定义
来源: https://www.cnblogs.com/LLFA/p/16390481.html