So I'm playing around with Eclipse's JDT API and trying to build a small app. However, I'm stuck when extracting data from the visited nodes since I can only print them.
I'd like to be able to, for example, return or add the value of getSuperclassType() to a List or HashMap. However, since the new ASTVisitor is an inner class, Java does not allow me to declare an Object used inside the ASTVisitor without the final keyword.
private static void get(String src) {
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(src.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.accept(new ASTVisitor() {
Set names = new HashSet();
public boolean visit(TypeDeclaration typeDecNode) {
if(!typeDecNode.isInterface()) {
System.out.println(typeDecNode.getName().toString());
System.out.println(typeDecNode.getSuperclassType());
System.out.println(typeDecNode.superInterfaceTypes().toString());
return true;
}
...
Is it possible from a piece of code like this to store the desired data from each visited node into a data structure? Or maybe another way to traverse the nodes from the AST without using the visitor pattern?
Just use a normal class extending
ASTVisitor
as the visitor instead of the anonymous class you are currently using and store whatever you like in the class.For example for the super types something like:
and use with:
Alternatively you can access a
final
list in an anonymous class like this: