Reputation: 2454
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. 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. I can see that A gets loaded only once while performing doInBackground() method. But, once control returns to someMethod(), the for loop iteration over the list throws a ClassCastException!! It goes like this:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Lcom.model.A; cannot be cast to 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!!
Need help! :(
Upvotes: 0
Views: 1694
Reputation: 10098
i think the system is complaining about an array being casted to a class *L*com.model.A; cannot be cast to com.model.A
please run the program in debug mode & see if you are getting an array in place of an object.
Upvotes: 2
Reputation: 63688
[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.
Upvotes: 4