How to access comments from the java compiler tree api generated ast?

前端 未结 5 2219
清歌不尽
清歌不尽 2020-12-30 17:37

I\'ve used the java compiler tree api to generate the ast for java source files. However, i\'m unable to access th comments in the source files.

So far, i\'ve been

5条回答
  •  难免孤独
    2020-12-30 18:25

    The comments obtained through getCommentList method of CompilationUnit will not have the comment body. Also the comments will not be visited, during and AST Visit. Inorder to visit the comments we have call accept method for each comment in the Comment List.

    for (Comment comment : (List) compilationUnit.getCommentList()) {
    
        comment.accept(new CommentVisitor(compilationUnit, classSource.split("\n")));
    }
    

    The body of the comments can be obtained using some simple logic. In the below AST Visitor for comments, we need to specify the Complied class unit and the source code of the class during initialization.

    import org.eclipse.jdt.core.dom.ASTNode;
    import org.eclipse.jdt.core.dom.ASTVisitor;
    import org.eclipse.jdt.core.dom.BlockComment;
    import org.eclipse.jdt.core.dom.CompilationUnit;
    import org.eclipse.jdt.core.dom.LineComment;
    
    public class CommentVisitor extends ASTVisitor {
    
        CompilationUnit compilationUnit;
    
        private String[] source;
    
        public CommentVisitor(CompilationUnit compilationUnit, String[] source) {
    
            super();
            this.compilationUnit = compilationUnit;
            this.source = source;
        }
    
        public boolean visit(LineComment node) {
    
            int startLineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
            String lineComment = source[startLineNumber].trim();
    
            System.out.println(lineComment);
    
            return true;
        }
    
        public boolean visit(BlockComment node) {
    
            int startLineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
            int endLineNumber = compilationUnit.getLineNumber(node.getStartPosition() + node.getLength()) - 1;
    
            StringBuffer blockComment = new StringBuffer();
    
            for (int lineCount = startLineNumber ; lineCount<= endLineNumber; lineCount++) {
    
                String blockCommentLine = source[lineCount].trim();
                blockComment.append(blockCommentLine);
                if (lineCount != endLineNumber) {
                    blockComment.append("\n");
                }
            }
    
            System.out.println(blockComment.toString());
    
            return true;
        }
    
        public void preVisit(ASTNode node) {
    
        }
    }
    

    Edit: Moved splitting of source out of the visitor.

提交回复
热议问题