1

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.

johnlinp
  • 853
  • 6
  • 22
  • What line throws the exception? – Jean-Baptiste Yunès May 20 '21 at 14:25
  • 1
    This sounds like a classloader problem. If those 2 classes where loaded by different classloaders casting will not work between them. This question seems to be about a similar problem (and a possible solution): https://stackoverflow.com/questions/25110407/issue-with-the-classloader-of-processingenvironment-from-maven – OH GOD SPIDERS May 20 '21 at 14:29
  • @OHGODSPIDERS "If those 2 classes where loaded by different classloaders casting will not work between them." Sorry, I'm not familiar with class loaders. May I ask if there's a pointer for me to see this statement? Thank you. – johnlinp May 21 '21 at 08:52
  • @OHGODSPIDERS I've made a quick demo to test this behavior: https://github.com/johnlinp/misc-demo/blob/master/two-class-loaders-load-same-class/. Thanks. – johnlinp May 24 '21 at 07:24

1 Answers1

1

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.

johnlinp
  • 853
  • 6
  • 22