Java casting / classloader issues

casting, classloader, java, java-native-interface, javax.imageio

Solution

I think it can happen if

- a `SomeClass` instance was loaded from ClassLoader X (so its class is `SomeClass` of CL X or let's call it: `CL(X).SomeClass`)

- but it is being cast in a different class loader. E.g. the current Threads class loader is Y so `SomeClass` is actually `CL(Y).SomeClass`

So you have:

- instance class = `CL(X).SomeClass`

- class cast target = `CL(Y).SomeClass`

Or in other words - not the same class - thus the class cast exception.

Possible duplicate of: ClassCastException when casting to the same class - it has some good suggestions as well.

Problem

Here is the simplified version of the problem: ``` SomeClass c = (SomeClass) obj.getSomeClassParent() ``` not always but it happens sometimes to trigger exception ``` org.somepackage.SomeClass can't be cast to org.somepackage.SomeClass ``` How is this possible ? I suppose it has something to do with the fact that JAI imageio is native lib, but relay how can this happen ? I'm probably missing something but what ? ``` I'm using JAI imageio version 1.1 dcm4che 2.0.21 DICOM lib ``` Here is the original code ``` ImageInputStream iis = ImageIO.createImageInputStream(src); Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM"); ImageReader reader = iter.next(); DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam(); ``` And the original exception ``` org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam can't be cast to org.dcm4che2.imageio.plugins.dcm.DicomImageReadParam ``` Exception Image http://img215.imageshack.us/img215/3894/exception.jpg

Original source

Related problems