本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!