本文介绍了eclipse ASTNode到源代码行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
你可以得到使用以下代码的ASTNode的行号
int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
可以使用以下代码获取编译单元
ASTParser parser = ASTParser.newParser(AST.JLS3);
//将类解析为编译单元。
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(source); //将您的java源代码作为char数组
parser.setResolveBindings(true);
//将编译的类作为编译单元返回
CompilationUnit compilationUnit = parser.createAST(null);
您可以使用以下代码访问节点(说MethodDeclaration节点):
compilationUnit.accept(new ASTVisitor(){
public boolean visit(MethodDeclaration node){
int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
return true;
}
});
Given an ASTNode in eclipse, is there any way to get the corresponding source code line number?
解决方案
You can get the line number of an ASTNode using the below code
int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
the compilation unit can be obtained using the below code
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);
You can visit the node (say MethodDeclaration node) using the below code:
compilationUnit.accept(new ASTVisitor() {
public boolean visit(MethodDeclaration node) {
int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
return true;
}
});
这篇关于eclipse ASTNode到源代码行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!