Why do I get a ClassCastException when parsing a tree?

If you get:

Exception in thread "main" java.lang.ClassCastException:
org.antlr.runtime.tree.CommonTree cannot be cast to MyCustomASTNode

It's probably because you forgot to set a custom tree adaptor in the node stream:



    /** An adaptor that tells ANTLR to build CymbalAST nodes */
    public static TreeAdaptor astAdaptor = new CommonTreeAdaptor() {
        public Object create(Token token) { return new GrammarAST(token); }
        public Object dupNode(Object t) {
            if ( t==null ) return null;
            return create(((GrammarAST)t).token);
        public Object errorNode(TokenStream input, Token start, Token stop,
                                RecognitionException e)
            return new GrammarASTErrorNode(input, start, stop, e);

If using a buffered stream, send into ctor:

        BufferedTreeNodeStream nodes = new BufferedTreeNodeStream(astAdaptor,myRootNode);