1、创建实例
public class MyPerson { private MyPerson myPerson; public void setMyPerson(Object obj){ this.myPerson = (MyPerson)obj; } }
2、创建测试类
public class MyTest20 { public static void main(String[] args) throws Exception { MyTest16 loader1 = new MyTest16("loader1"); MyTest16 loader2 = new MyTest16("loader2"); Class<?> clazz1 = loader1.loadClass("com.example.jvm.classloader.MyPerson"); Class<?> clazz2 = loader2.loadClass("com.example.jvm.classloader.MyPerson"); System.out.println( clazz1 == clazz2); Object object1 = clazz1.newInstance(); Object object2 = clazz2.newInstance(); Method method = clazz1.getMethod("setMyPerson", Object.class); method.invoke(object1, object2); } }
3、MyTest16类和之前的一致
public class MyTest16 extends ClassLoader{ private String className; //目录 private String path; private final String fileExtension = ".class"; public MyTest16(String classLoadName){ super(); //将系统类加载器当做该类加载器的父加载器 this.className = classLoadName; } public MyTest16(ClassLoader parent, String classLoadName){ super(parent); //显示指定该类加载器的父加载器器 this.className = classLoadName; } public void setPath(String path) { this.path = path; } @Override public String toString() { return "[" + this.className + "]"; } @Override protected Class<?> findClass(String clasName) throws ClassNotFoundException { System.out.println("findClass invoked:" + clasName); System.out.println("class loader name: " + this.className); byte[] data = this.loadClassData(clasName); return this.defineClass(clasName,data, 0, data.length); } private byte[] loadClassData(String className){ InputStream is = null; byte[] data = null; ByteArrayOutputStream baos = null; try{ className = className.replace(".","//"); //System.out.println("className:" +this.className); is = new FileInputStream(new File(this.path + className + this.fileExtension)); baos = new ByteArrayOutputStream(); int ch = 0; while ( -1 != (ch = is.read())){ baos.write(ch); } data = baos.toByteArray(); }catch (Exception ex){ ex.printStackTrace(); }finally { try { is.close(); baos.close(); }catch (Exception ex){ ex.printStackTrace(); } } return data; } }View Code
打印结果
true