2012-06-20 1 views
4

에 이클립스 ASTNode 이클립스에서 ASTNode가 주어지면 해당 소스 코드 행 번호를 얻는 방법이 있습니까?소스 코드 행 번호

답변

1

ASTNode에는 문자 오프셋을 처리하는 getStartPosition() 및 getLength() 메소드가 있습니다. 문자 오프셋을 행 번호로 변환하려면 CompilationUnit의 getLineNumber() 메소드를 사용해야합니다. CompilationUnit은 AST 트리의 루트입니다.

15

당신은 (MethodDeclaration 노드 말하는 컴파일 단위 당신은 노드를 방문 할 수 있습니다

ASTParser parser = ASTParser.newParser(AST.JLS3); 

    // Parse the class as a compilation unit. 
    parser.setKind(ASTParser.K_COMPILATION_UNIT); 
    parser.setSource(source); // give your java source here as char array 
    parser.setResolveBindings(true); 

    // Return the compiled class as a compilation unit 
    CompilationUnit compilationUnit = parser.createAST(null); 

아래의 코드를 사용하여 얻을 수

int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1; 

아래의 코드를 사용하여 ASTNode의 줄 번호를 얻을 수 있습니다) 아래 코드를 사용하여 :

compilationUnit.accept(new ASTVisitor() { 

     public boolean visit(MethodDeclaration node) {  
      int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1; 
      return true; 
     } 
    }); 
1

예를 들어, ASTNode의 앞에 작성된 선행 공백이나 잠재적 주석을 포함하여 ASTNode의 행 번호가 필요한 경우 적용되는 또 다른 것이 있습니다. 그럼 당신은 사용할 수 있습니다

주어진 노드의 확장 된 시작 위치를 반환

int lineNumber = compilationUnit.getLineNumber(compilationUnit.getExtendedStartPosition(astNode)) 

API 참조. ASTNode.getStartPosition() 및 ASTNode.getLength()와 달리 확장 소스 범위에는 노드의 정상 소스 범위 바로 앞이나 뒤의 주석 및 공백이 포함될 수 있습니다.