johnlinp
johnlinp

Reputation: 933

When will an object fail to cast to its parent class in Java?

I'm having the same issue as ClassCastException in ant schemagen task using jaxb-ri-2.2.7. However, my biggest question is not about the issue itself, but the exception in the error log:

java.lang.ClassCastException: com.sun.tools.javac.api.JavacTrees cannot be cast to com.sun.source.util.Trees

By looking into the problem, I found that JavacTrees is a child class of DocTrees, and DocTrees is a child class of Trees. Specifically, the class definitions are:

public class JavacTrees extends DocTrees {
    // ...
}

public abstract class DocTrees extends Trees {
    // ...
}

public abstract class Trees {
    // ...
}

The above ClassCastException basically means that an object failed to cast into its parent class. I don't remember anything like that in any textbook I read.

Can somebody explain this exception to me? Thanks.

Upvotes: 1

Views: 495

Answers (1)

johnlinp
johnlinp

Reputation: 933

Thanks @OHGODSPIDERS for the hint about ClassLoaders. I checked the class loaders of JavacTrees and Trees using a debugger, and here's the results:

Therefore, the 2 classes are loaded by different ClassLoaders. Hence it will fail to cast from JavacTrees to Trees, even though Trees is the parent class of JavacTrees.

Upvotes: 0

Related Questions