简体   繁体   中英

ASTVisitor does not return any Comments in Eclipse Plugin

In my Eclipse plugin I want to parse the comments in a CompilationUnit. My other visitors (eg ForVisitor, VariableDeclarationVisitor, etc.) work just fine - but my CommentVisitor does not return anything.

AST and ASTVisitor creation (works for all others visitors)

void createAST(ICompilationUnit unit) throws JavaModelException {
    CompilationUnit parse = parse(unit);

    // return all comments
    CommentVisitor visitor = new CommentVisitor();
    parse.accept(visitor);
    System.out.println(parse.getCommentList().toString());
    for(LineComment lineComment : visitor.getLineComments()) {
        lineComment.accept(visitor);  // a try to make it work
        System.out.println("Line Comment: " + lineComment.getLength());
    }
    System.out.println("---------------------------------");
    for(BlockComment blockComment : visitor.getBlockComments()) {
        System.out.println("Block Comment: " + blockComment.getLength());
    }
}

CompilationUnit parse(ICompilationUnit unit) {
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(unit);
    parser.setResolveBindings(true);
    return (CompilationUnit) parser.createAST(null); // parse
}

CommentVisitor.java (generally the same syntax as all the other visitors)

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.BlockComment;
import org.eclipse.jdt.core.dom.LineComment;

public class CommentVisitor extends ASTVisitor {
    List<LineComment> lineComments = new ArrayList<LineComment>();
    List<BlockComment> blockComments = new ArrayList<BlockComment>();

    @Override
    public boolean visit(LineComment node) {
            lineComments.add(node);
            return super.visit(node);
    }

    @Override
    public boolean visit(BlockComment node) {
            blockComments.add(node);
            return super.visit(node);
    }

    public List<LineComment> getLineComments() {
            return lineComments;
    }

    public List<BlockComment> getBlockComments() {
            return blockComments;
    }
}

To clarify my problem again: I do not get any reaction from the code above - not even empty Strings, which was the topic in a few other questions here on SO.

Refer to this page to find the answer.

 public boolean visit(LineComment node) {
        int start = node.getStartPosition();
        int end = start + node.getLength();
        // source is a string representing your source code
        String comment = source.substring(start, end);
        System.out.println(comment);
        return true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM