2
在我的Eclipse插件中,我想分析CompilationUnit中的註釋。我的其他訪問者(例如ForVisitor,VariableDeclarationVisitor等)工作得很好 - 但我的CommentVisitor不返回任何內容。ASTVisitor在Eclipse插件中不返回任何評論
AST和創造的ASTVisitor(適用於所有其他遊客)
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(大致相同的語法,因爲所有其他訪問者)
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;
}
}
爲了澄清我問題再次出現:我沒有從上面的代碼中得到任何反應 - 甚至沒有空字符串,這是這裏關於SO的其他幾個問題的主題。