Getting this error at Java runtime:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: class org.apache.batik.swing.JSVGCanvas cannot be cast to class org.apache.batik.swing.svg.SVGLoadEventDispatcherListener (org.apache.batik.swing.JSVGCanvas and org.apache.batik.swing.svg.SVGLoadEventDispatcherListener are in unnamed module of loader 'app')

Code:

private void handleSVGs(JSVGCanvas canvas) { 
    canvas.addSVGLoadEventDispatcherListener((SVGLoadEventDispatcherListener) this.canvas1);
}

One of the earlier compiled versions of this code runs. But after re-compiling the same code, it throws above error during run-time, not compile time.

1

There are 1 best solutions below

0
kjsmita6 On

The error message is pretty clear,

org.apache.batik.swing.JSVGCanvas cannot be cast to class org.apache.batik.swing.svg.SVGLoadEventDispatcherListener

These classes are not at all related (https://xmlgraphics.apache.org/batik/javadoc/org/apache/batik/swing/JSVGCanvas.html and https://xmlgraphics.apache.org/batik/javadoc/org/apache/batik/swing/svg/SVGLoadEventDispatcher.html).

You are not allowed to cast any object to any type, they must have a similar hierarchy. In the classic example of Animal, Dog, and Cat, you are not allowed to say that this Dog is a Cat (you can say that the Dog is an Animal though).

If you want to be sure, check

if (this.canvas1 instanceof SVGLoadEventDispatcherListener) {
    System.out.println("You can cast!");
else {
    System.out.println("Casting not allowed");
}

It's recommended to do this if the type of something is ever dubious or if the parameter of a function is an interface but you need a specific concrete type.