在我的Eclipse插件中,我想解析CompilationUnit中的注释。我的其他访问者(例如ForVisitor,VariableDeclarationVisitor等)工作正常 - 但我的CommentVisitor没有返回任何内容。
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的其他几个问题的主题。
答案 0 :(得分:0)
请参阅此page以找到答案。
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;
}