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! :(