JAI imageio casting problem

I recently had problems using Java Advanced Imaging (JAI).
Here is the simplified version of the problem, so we have:
SomeClass c = (SomeClass) obj.getSomeClassParent()
it happens sometimes to trigger exception

org.somepackage.SomeClass can't be cast to org.somepackage.SomeClass 

Original code:

ImageInputStream iis = ImageIO.createImageInputStream(src);
Iterator 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 



The problem was that I was missing that sometime the class is loaded by different class loader and it can happen that the casted class is not the same whit the one form the default class loader. Now this would have been obvious if it was in two different vm's , or maybe some object received via de/serialization ...

The question on StackOverflow

Popular Posts