package shenqi; import java.io.*; /** * Created by shenqi on 18/6/2. */ public class MyClassLoader extends ClassLoader{ private String path; //类加载路径 private String classLoadName; //类加载器名称 //让系统类加载器作为该类的父加载器 public MyClassLoader(String path,String classLoadName){ super(); this.path = path; this.classLoadName = classLoadName; } //指定当前类的父类加载器 public MyClassLoader(ClassLoader parent,String path,String classLoadName){ super(parent); this.path = path; this.classLoadName = classLoadName; } /** * 记录自定义的类,通过自定义加载器去加载 * @param name * @return * @throws ClassNotFoundException */ @Override protected Class<?> findClass(String name) throws ClassNotFoundException{ byte [] data = readClassFileToByteArray(name); return this.defineClass(name,data,0,data.length); } /** * 从文件目录获取.class字节文件数组 * @param name * @return */ private byte [] readClassFileToByteArray(String name){ InputStream is = null; byte [] data = null; name = name.replaceAll("\\.","/"); String filePath = this.path + path + ".class"; File file = new File(filePath); ByteArrayOutputStream os = new ByteArrayOutputStream(); try{ is = new FileInputStream(file); int temp = 0; while((temp = is.read()) != -1){ os.write(temp); } data = os.toByteArray(); }catch (Exception e){ e.printStackTrace(); }finally { try { if (is != null){ is.close(); } if (os != null){ os.close(); } }catch (IOException e){ e.printStackTrace(); } } return data; } }
自己写一个自定义类加载器
最新推荐文章于 2024-05-14 08:53:32 发布