写一个自定义类加载器demo
public class MyTest16 extends ClassLoader { private String classLoaderName; private String fileExtension = ".class"; private String path; public MyTest16(String classLoaderName) { super(); // 将系统类加载器当做该类加载器的父类加载器 this.classLoaderName = classLoaderName; } public void setPath(String path){ this.path = path; } public MyTest16(ClassLoader parent, String classLoaderName) { super(parent); //显示指定该类的加载器的父类加载器 this.classLoaderName = classLoaderName; } private byte[] loadClassData(String className) { InputStream is = null; byte[] data = null; ByteArrayOutputStream baos = null; String classNameResult = className.replace(".", "\\"); System.out.println(classNameResult); try { //注意win和linux this.classLoaderName = this.classLoaderName.replace(".", "\\"); //指定磁盘全路径 String fileUrl = classNameResult + this.fileExtension; is = new FileInputStream(this.path + new File(fileUrl)); baos = new ByteArrayOutputStream(); int ch ; while (-1 != (ch = is.read())) { baos.write(ch); } // 字节数组输出流转换成字节数组 data = baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); baos.close(); } catch (Exception e) { e.printStackTrace(); } } return data; } @Override protected Class<?> findClass(String className) throws ClassNotFoundException { System.out.println("findClass invoked:" + className); System.out.println("class loader name" + this.classLoaderName); byte[] data = this.loadClassData(className); //返回Class对象 return this.defineClass(className, data, 0 , data.length); } @Override public String toString() { return "[" + this.classLoaderName + "]"; } public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException { // 创建自定义类加载器 名字“loader1” 父类加载器是系统类加载器 MyTest16 loader1 = new MyTest16("loader1"); //此路径为classPath,故 findClass方法不会被调用执行! 如果换个路径,不是classPath就会去执行了! loader1.setPath("D:\\eclipse_pj\\dianshang\\jvmTest\\out\\production\\jvmTest\\"); Class<?> clazz = loader1.loadClass("com.jvm.t1.MyTest15"); System.out.println("class:"+ clazz.hashCode()); Object object = clazz.newInstance(); System.out.println(object); // loader1 指向新的实例 loader1 = new MyTest16("loader1"); //此路径为classPath,故 findClass方法不会被调用执行! 如果换个路径,不是classPath就会去执行了! loader1.setPath("D:\\eclipse_pj\\dianshang\\jvmTest\\out\\production\\jvmTest\\"); //指向新的 clazz = loader1.loadClass("com.jvm.t1.MyTest15"); System.out.println("class:"+ clazz.hashCode()); // 指向新的 object = clazz.newInstance(); System.out.println(object); } }
调用:
public class Test17 { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException { MyTest16 loader1 = new MyTest16("loader1"); loader1.setPath("D:\\test\\jvm\\"); Class<?> clazz = loader1.loadClass("com.jvm.t1.test"); System.out.println("class"+ clazz.hashCode()); Object o = clazz.newInstance(); } }