Extracting data from Eclipse's JDT visitor pattern

448 views Asked by At

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?

1

There are 1 answers

0
greg-449 On BEST ANSWER

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:

class MyVisitor extends ASTVisitor
{
  private List<Type> superTypes = new ArrayList<>();

  @Override
  public boolean visit(TypeDeclaration typeDecNode) {
       if(!typeDecNode.isInterface()) {
            superTypes.add(typeDecNode.getSuperclassType());
            return true;
       }
  }

  List<Type> getSuperTypes() {
     return superTypes;
  }
}

and use with:

MyVisitor myVisitor = new MyVisitor();

cu.accept(myVisitor);

List<Type> superTypes = myVisitor.getSuperTypes();

Alternatively you can access a final list in an anonymous class like this:

final List<Type> superTypes = new ArrayList<>();

cu.accept(new ASTVisitor() {
     public boolean visit(TypeDeclaration typeDecNode) {
        if(!typeDecNode.isInterface()) {
            superTypes.add(typeDecNode.getSuperclassType());

            return true;
        }