Less casting in JavaParser

Less casting in JavaParser

A common pattern in code using JavaParser looks as follows:

Federico Tomassetti, who maintains Java Symbol Solver, suggested we move some helpful methods from that project to JavaParser so that we can do this:

Not only is this much more pleasing to the eye, your IDE will suggest these methods for you, so you can pick the correct sub-node without having to go through the class hierarchy.

I thought we could use Java 8 to improve it even more:

cond has the correct type and is ready to be used right away 🙂

These methods are available at most nodes. I did not implement them on Node or other very wide types because the amount of methods would explode, and that would not be helpful to anyone. (statement.isExpression()?!)

Have fun cleaning up your code!

Addendum 🙂

From 3.5.6 on, there are “to” methods that return an Optional, so now you can do this kind of trickery:

This will help you get rid of .get()‘s everywhere.

Be the first to comment

Leave a Reply