ANTLR parsers produce the following generated code:
protected TreeAdaptor adaptor = new CommonTreeAdaptor();
I’ve implemented my own TreeAdaptor, and I want the parser to always use mine and never use CommonTreeAdaptor(). The only method I’ve found is to set it inside the calling code every time I create a new parser:
Parser parser = new MyParser();
parser.setTreeAdaptor(new MyAdaptor());
Is there some way I can set the default TreeAdaptor or append some initialization code to the generated constructor?
I think I’ve found a better solution than Bart’s named-constructor method.
I’m not able to modify the generated constructor directly (including to make it private, which is why I dislike the named-constructor solution). However, I can introduce an initialization block:
According to the Java documentation, “The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.”
So
this.adaptorwill first be set tonew CommonTreeAdaptor()by the generated code, but will then be set tonew MyAdaptor()by my initialization block. Testing confirms that this is what actually happens.The advantage of this solution is that callers of my parser don’t need to be aware that it’s using a custom TreeAdaptor or doing anything out of the ordinary (my adaptor is a subclass of CommonTreeAdaptor, so any code dependent on that is fine).