I'm get a ClassCastException
whenever I try to cast a BufferedImage (parent) to an AdvancedBufferedImage (child) which I extended myself, I've not overridden any methods and I've implemented all the contractors without modifying them
I'm gettign this exception whenever I try to create an AdvancedBufferedImage out of File using ImageIO.read() method.
File file = new file(path);
AdvancedBufferedImage image = (AdvancedBufferedImage) ImageIO.read(file);
It seems there should not be any problem, What could be the problem?
downcast is allowed, but it must a actual instance of the child:
class A {
String name = "a";
A(){};
}
class B extends A {
}
public class Main {
public static void main(String[] args) {
A a = new B(); // must a b instance
B b = new B();
b = (B)a;
System.out.println(b.name);
}
}
Downcasting like this is not allowed.
The preferred solution would be to create a constructor of AdvancedBufferedImage, taking a BufferedImage as parameter. With that you could do the following.
File file = new file(path);
AdvancedBufferedImage image = new AdvancedBufferedImage(ImageIO.read(file));
Here the constructor of AdvancedBufferedImage can decide how to properly convert a BufferedImage in an advanced one..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With