自定义ClassLoader

Posted INEFFABLE LAND

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义ClassLoader相关的知识,希望对你有一定的参考价值。

自定义classloader

MapleClassLoader

package com.maple;

import java.io.*;

public class MapleClassLoader extends ClassLoader {

    private String path = "E:\\Workspaces\\loader\\target\\classes\\";

    public MapleClassLoader(String path){
        this.path = path ;
    }

    public MapleClassLoader(ClassLoader parent,String path){
        super(parent);
        this.path = path;
    }


    /*@Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] data = loadClassData(name);
        return defineClass(name,data,0,data.length);
    }*/


    /*private byte[] loadClassData(String name) {
        try {
            name = name.replaceAll(".", "\\");
            FileInputStream is = new FileInputStream(new File(path + name + ".class"));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int b;
            while ((b = is.read()) != -1) {
                bos.write(b);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        try {
            String fileName = name.replaceAll("\\.", "\\/");
            FileInputStream is;
            try {
                is = new FileInputStream(new File(path + fileName + ".class"));
            } catch (Exception e) {
                is = null;
            }


            if (is == null) {
                return super.loadClass(name);
            }

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int b;
            while ((b = is.read()) != -1) {
                bos.write(b);
            }
            byte[] data = bos.toByteArray();

            return defineClass(name, data, 0, data.length);
        } catch (Exception e) {
            throw new ClassNotFoundException(name);
        }
    }
}

测试

public class Demo1 {

    public static void main(String[] args) throws Exception {
        MapleClassLoader mc = new MapleClassLoader(Thread.currentThread().getContextClassLoader(),"E:\\Workspaces\\loader\\target\\classes\\");
        Object obj = (Object)mc.loadClass("com.maple.Demo1").newInstance();
        System.out.println("load: "+ obj.getClass());
        System.out.println("local: "+ Demo1.NUM);
        System.out.println(obj instanceof Demo1);
    }

    private static int NUM = 1;

    private static Integer addNum(){
        return NUM++;
    }
}

测试结果

load: class com.maple.Demo1
local: 1
false

以上是关于自定义ClassLoader的主要内容,如果未能解决你的问题,请参考以下文章

自定义类加载器classLoader

自定义ClassLoader

自定义ClassLoader

VSCode自定义代码片段——CSS选择器

classloader加载class的流程及自定义ClassLoader

VSCode自定义代码片段6——CSS选择器