赞
踩
原因
需要转换的类不在同一个类加载器名称空间
案例
public class MyPerson {
private MyPerson myPerson;
public void setMyPerson(Object object) {
this.myPerson = (MyPerson)object;
}
}
当我们使用自定义类加载器加载这个MyPerson类
public static void main(String[] args) throws Exception {
MyClassLoad classLoad1 = new MyClassLoad("classload1");
MyClassLoad classLoad2 = new MyClassLoad("classload2");
classLoad1.setPath("C:\\Users\\3C\\Desktop\\");
classLoad2.setPath("C:\\Users\\3C\\Desktop\\");
Class<?> aClass1 = classLoad1.loadClass("com.MyPerson");
Class<?> aClass2 = classLoad2.loadClass("com.MyPerson");
System.out.println(aClass1 == aClass2);
Method setMyPerson = aClass1.getMethod("setMyPerson", Object.class);
setMyPerson.invoke(aClass1.newInstance(), aClass2.newInstance());
}
运行结果
使用自定义加载器加载了:com.MyPerson
使用自定义加载器加载了:com.MyPerson
false
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.Test1.main(Test1.java:18)
Caused by: java.lang.ClassCastException: com.MyPerson cannot be cast to com.MyPerson
at com.MyPerson.setMyPerson(MyPerson.java:7)
... 5 more
结论分析
因为两个自定义加载器对象加载的同一个类的class文件并不在同一个名称空间(内存),所以当加载器1new出来的对象想要调用setMyPerson方法需要传递的是加载器1名称空间中的MyPerson对象
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。