JVM学习笔记15——自定义类加载器深入详解
发布日期:2021-06-29 01:18:52 浏览次数:2 分类:技术文章

本文共 2757 字,大约阅读时间需要 9 分钟。

The ClassLoader class uses a delegation model to search for classes and resources. Each instance of ClassLoader has an associated parent class loader. When requested to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself. The virtual machine's built-in class loader, called the "bootstrap class loader", does not itself have a parent but may serve as the parent of a ClassLoader instance.

However, some classes may not originate from a file; they may originate from other sources, such as the network, or they could be constructed by an application. The method defineClass converts an array of bytes into an instance of class Class. Instances of this newly defined class can be created using Class.newInstance.

实现一个自定义类加载器

public class MyTest16 extends ClassLoader{    private String classLoaderName;    private final String fileExtension = ".class";    public MyTest16(String classLoaderName){        super(); // 将系统类加载器当做该类加载器的父类加载器        this.classLoaderName = classLoaderName;    }    public MyTest16(ClassLoader parent, String classLoaderName){        super(parent); // 显式指定父类加载器        this.classLoaderName = classLoaderName;    }    @Override    public String toString() {        return "MyTest16{" + "classLoaderName='" + classLoaderName + '\'' + '}';    }    @Override    protected Class
findClass(String className) throws ClassNotFoundException { byte[] bytes = this.loadClassDate(className); return this.defineClass(className,bytes,0,bytes.length); } private byte[] loadClassDate(String name){ InputStream is = null; byte[] data = null; ByteArrayOutputStream baos = null; try { this.classLoaderName = this.classLoaderName.replace(".","/"); is = new FileInputStream(new File(name + this.fileExtension)); baos = new ByteArrayOutputStream(); int ch = 0; while(-1 != (ch = is.read())){ baos.write(ch); } data = baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); }finally { try { is.close(); baos.close(); } catch (IOException e) { e.printStackTrace(); } } return data; } public static void test(ClassLoader classLoader) throws Exception{ Class
clazz = classLoader.loadClass("com.yshuoo.jvm.classloader.MyTest1"); Object o = clazz.newInstance(); System.out.println(o); } public static void main(String[] args) throws Exception{ MyTest16 myTest16 = new MyTest16("loader1"); test(myTest16); }}

转载地址:https://blog.csdn.net/yshuoo/article/details/116518437 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:JVM学习笔记16——类加载器重要方法详解
下一篇:JVM学习笔记14——ClassLoader源码分析与实例剖析

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月18日 12时20分37秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章