[英]What is wrong with my classloader? ClassCastException when casting to the same class!
Before anyone closes this is a duplicate of this , please hold your horses, this is a little different:-)在任何人关闭之前这是一个副本,请保持你的马,这有点不同:-)
I have a class A which is being used in a SwingWorker.我有一个在 SwingWorker 中使用的 class A。 So, the program kinda looks like this:
所以,程序有点像这样:
class Task extends SwingWorker {
public Task(ClassLoader loader) {
Thread.currentThread().setContextClassLoader(loader);
}
public List<A> doInBackground() {
A obj = new A();
//do some stuff with A;
return list of A;
}
}
And my method which invokes this task looks like this:我调用此任务的方法如下所示:
public void someMethod() throws Exception {
Task task = new Task(Thread.getCurrentThread().getContextClassLoader():
//do something and wait for output
List<A> result = task.get();
for(A obj : result) {
//do something
}
}
Now, I did a java -verbose:class, to see how this class was getting loaded.现在,我做了一个 java -verbose:class,看看这个 class 是如何被加载的。 I can see that A gets loaded only once while performing doInBackground() method.
我可以看到 A 在执行 doInBackground() 方法时只加载一次。 But, once control returns to someMethod(), the for loop iteration over the list throws a ClassCastException:!
但是,一旦控制返回到 someMethod(),列表上的 for 循环迭代就会抛出 ClassCastException:! It goes like this:
它是这样的:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Lcom.model.A;
线程“AWT-EventQueue-0”中的异常 java.lang.ClassCastException:[Lcom.model.A; cannot be cast to com.model.A]
不能转换为 com.model.A]
I have no idea why this doesn't work.我不知道为什么这不起作用。 I tried using Class.forName() and preloading class A in someMethod(), before invoking a SwingWorker, while doing this without passing the classloader instance, the same class was getting loaded twice,, After sending the classloader as param, the class gets loaded only once precisely, but refuses to cast!!
I tried using Class.forName() and preloading class A in someMethod(), before invoking a SwingWorker, while doing this without passing the classloader instance, the same class was getting loaded twice,, After sending the classloader as param, the class gets只加载一次,但拒绝施放!!
Need help: :(需要帮忙: :(
[Lcom.model.A; cannot be cast to com.model.A]
^^
You are trying to cast the com.model.A[]
instance to com.model.A
instance.您正在尝试将
com.model.A[]
实例转换为com.model.A
实例。
i think the system is complaining about an array being casted to a class * L *com.model.A;我认为系统抱怨一个阵列被投射到 class * L *com.model.A; cannot be cast to com.model.A
不能转换为 com.model.A
please run the program in debug mode & see if you are getting an array in place of an object.请在调试模式下运行程序并查看您是否获得了一个数组来代替 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.