Conversions between trees and elements and types…
Sometimes you need to go from element to a tree, or from a type to an element and vice versa.
-
Going from a Tree to an Element use com.sun.source.util.Trees.getElement( TreePath ). Notice that you lose all the type information in case the class/method uses generics so you may be interested in instead using a Type rather than an Element.
-
Going from a Tree to a Type use com.sun.source.util.Trees.getType( TreePath )
-
Going from an Element to a Tree use one of the ( com.sun.source.util.Trees.getTree( … ) methods.
-
Going from an Element to a Type is easy; what you need to do is to call the asType() method on the Element.
-
Going from a Type to an Element you can do this with DeclaredType instances by calling their asElement() method
PITFALL Methods for going from a Tree to an Element or a Type require TreePath
It is not enough to send the Tree as a parameter. There are basically several ways how to get a TreePath:
-
If you know the CompilationUnit call com.sun.source.util.Trees.getPath( CompilationUnitTree, Tree )
-
If you know the Element you can call com.sun.source.util.Trees.getPath( Element )
-
If you are going through the tree using a visitor or scanner you may rather want to subclass the com.sun.source.util.TreePathScanner class which will permit for getting the current path at any time using it’s getCurrentPath() method.