自定义类加载器加载的clazz为什么构造反射出来的对象不能强转?
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException {
MyClassloader myClassloader = new MyClassloader("D:\\javacode3\\thread-exercise\\target\\classes\\com\\karson\\test\\");
Class<?> garbage = myClassloader.loadClass("Garbage");
Method say = garbage.getDeclaredMethod("say");
Object instance = garbage.getDeclaredConstructor().newInstance();
if (instance instanceof Garbage){
System.out.println("yes");
}
say.invoke(instance,null);
System.out.println(instance);
System.out.println(garbage.getClassLoader());
}
//报错信息
hello
Exception in thread "main" java.lang.ClassCastException: com.karson.test.Garbage cannot be cast to com.karson.test.Garbage
at com.karson.test.TT.main(TT.java:32)
//如下是自己定义的类加载加载指定目录下的.class文件
public class MyClassloader extends ClassLoader {
private String byteCodePath;
public MyClassloader(String byteCodePath) {
this.byteCodePath = byteCodePath;
}
public MyClassloader(ClassLoader parent, String byteCodePath) {
super(parent);
this.byteCodePath = byteCodePath;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String path = byteCodePath + name + ".class";
BufferedInputStream bis = null;
ByteArrayOutputStream bao = null;
try {
bis = new BufferedInputStream(new FileInputStream(path));
bao = new ByteArrayOutputStream();
int len;
byte[] data = new byte;
while ((len = bis.read(data)) != -1){
bao.write(data,0,len);
}
byte[] byteCodes = bao.toByteArray();
return defineClass(null,byteCodes,0,byteCodes.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bao != null){
try {
bao.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
} 类加载器不同导致类型强制转换报错:java.lang.ClassCastException
试着运行了下,没报错:
Twilight6 发表于 2022-11-30 10:25
试着运行了下,没报错:
仔细看了一下,你加载Garbage这个类的加载器并不是我定义的类加载器,还是使用的是appClassLoader,我的显示加载器用的是com.karson.test.MyClassloader@29453f44 我爱吃爆米花 发表于 2022-11-30 10:40
仔细看了一下,你加载Garbage这个类的加载器并不是我定义的类加载器,还是使用的是appClassLoader,我的 ...
好吧
页:
[1]