栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自定义类加载器实现(Java)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自定义类加载器实现(Java)

方法:

  • 重写loadclass方法,不推荐因为会破坏双亲委派模型
  • 重写findClass方法,推荐
public class MyClassLoader extends ClassLoader{

    //1
    private String codePath;

    //2.
    public MyClassLoader(ClassLoader parent, String codePath) {
        super(parent);
        this.codePath = codePath;
    }

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


    @Override
    protected Class findClass(String name) throws ClassNotFoundException {
        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = null;

        try {
            //1.字节码路径
            String fileName = codePath + name + ".class";
            //获取输入流
            bis = new BufferedInputStream(new FileInputStream(fileName));
            //获取输出流
            baos = new ByteArrayOutputStream();
            //进行io读写
            int len;
            byte[] data = new byte[1024];
            while ((len = bis.read(data)) != -1){
                baos.write(data,0,len);
            }
            //获取内存中的字节数组
            byte[] byteCode = baos.toByteArray();
            //调用defineClass将字节数组转成Class对象
            Class defineClass = defineClass(null, byteCode, 0, byteCode.length);
            //返回
            return defineClass;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
}

public class String {
    static {
        System.out.println("自定义的String...");
    }
}

测试:

public class MyClassLoaderTest {
    public static void main(String[] args) {
        MyClassLoader classLoader = new MyClassLoader("d:/");
        try {
            Class clazz = classLoader.loadClass("String");
            System.out.println("由:" + clazz.getClassLoader().getClass().getName() + "加载的");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

结果:

由:com.zzyuan.lagou.util2.MyClassLoader加载的
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/851264.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号