一般情况下在程序中开发人员使用自己编写的自定义加载器来与默认的加载器共同执行类加载任务的情况并不多见。实现一个自定义类加载器是非常简单的,只需要继承抽象类ClassLoader,并重写其findClass()方法即可。

自定义加载器的编码实现


//自定义类加载器 myClassLoader
public class MyClassLoader extends ClassLoader{

    private String codePath;


    public MyClassLoader(String codePath) {
        this.codePath = codePath;
    }

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

        byte[] value = null;
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(codePath+name+".class"));
            value = new byte[in.available()];
            in.read(value);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        assert value != null;
        return defineClass(this.getClass().getPackageName()+"."+name,value,0,value.length);
    }


    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        MyClassLoader myClassLoader = new MyClassLoader("/xxx/xxx/");
        Class carClass  = myClassLoader.loadClass("Car");
        Object o = carClass.getDeclaredConstructor(new Class[]{String.class}).newInstance(new String[]{"hello"});
        Method method = o.getClass().getMethod("run");
        method.invoke(o);

        System.out.println(o.getClass().getClassLoader());
        
        System.out.println(myClassLoader.getClass().getClassLoader());

    }

}