2017-01-05 12 views
0

그래서 Eclipse의 JDT API로 놀고 있고 작은 애플리케이션을 빌드하려고합니다. 그러나 방문한 노드에서만 데이터를 추출 할 수 있기 때문에 데이터를 추출 할 때 막혔습니다.Eclipse의 JDT 방문자 패턴에서 데이터 추출하기

예를 들어 getSuperclassType() 값을 List 또는 HashMap에 반환하거나 추가 할 수 있기를 원합니다. 그러나 새로운 ASTVisitor는 내부 클래스이기 때문에 Java는 최종 키워드없이 ASTVisitor 내부에서 사용되는 Object를 선언 할 수 없습니다.

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; 
      } 
... 

이와 같은 코드를 통해 방문한 각 노드의 원하는 데이터를 데이터 구조에 저장할 수 있습니까? 방문자 패턴을 사용하지 않고 AST에서 노드를 통과하는 또 다른 방법은 없을까요?

답변

2

현재 익숙한 클래스 대신 방문자로 ASTVisitor을 확장 한 일반 클래스를 사용하고 클래스에 원하는 것을 저장하십시오. 같은 슈퍼 유형 뭔가 예를 들어

:

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

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

      return true; 
     } 
:이 같은 익명 클래스의 final 목록에 액세스 할 수 있습니다 또는

MyVisitor myVisitor = new MyVisitor(); 

cu.accept(myVisitor); 

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

:

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; 
    } 
} 

와 함께 사용