[英]How get line from parsed java source from Eclipse JDT Parser?
[英]How to obtain line and/or column from parsed java source from Eclipse JDT Parser from all nodes?
我已經使用AST玩了很長時間了,並且試圖從eclipse中獲取與此插件解析的給定節點相關的行和列信息。 根據此處記錄的api ,我發現方法getStartPosition()
可以為我提供已解析文件的字符位置,但這不是我想要的。
我繼續查看CompilationUnit類的api文檔,以找出方法getLineNumber(int position)
和getColumnNumber(int position)
,據我所知,它們可以解決問題。 通過執行node.getStartPosition()
, position
參數等於getStartPosition()
方法返回的內容。
現在,問題在於在源文件上獲取行和列的兩種方法似乎並非對所有節點都可用。 例如, 方法聲明節點沒有它們!
如何在所有樹上獲取此類信息? 我知道這並非不可能,因為我能夠對其他語言使用解析器,因為每個 ast節點都有與之關聯的行和列。 實際上,我相信javaparser是Java的其中之一,因為該類包含行和列的硬編碼屬性。 看到Eclipse JDT對我來說似乎更強大,並且在那里呆了相當長的一段時間,令我驚訝的是無法獲得此類信息。
編輯:再次,問題是從僅出現在根目錄上的編譯單元的不同東西獲取行號:
<type 'org.eclipse.jdt.core.dom.CompilationUnit'>
1
<type 'org.eclipse.jdt.core.dom.TypeDeclaration'>
<type 'org.eclipse.jdt.core.dom.Javadoc'>
<type 'org.eclipse.jdt.core.dom.TagElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
<type 'org.eclipse.jdt.core.dom.TextElement'>
謝謝。
為了后代,我將重新發布在jdt-core-dev郵件列表中的答案。 (我的回答與以上Ryan的建議並沒有很大不同)
嗨,卡洛斯,
您對CompilationUnit.getLineNumber(int)方法是正確的。 您可以如下使用它:
int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()) - 1;
但是,我不明白您的位置。 為什么需要為MethodDeclaration定義getLineNumber(..)? 您所要做的就是找到方法聲明節點,然后使用下面的代碼為其找到對應的CompilationUnit,然后使用上面的代碼行找到行號。 我在這里想念什么嗎?
ASTParser parser = ASTParser.newParser(AST.JLS3); // or JLS_4 for java 7 and above
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(source); // give your java source here as char array
parser.setResolveBindings(true);
CompilationUnit compilationUnit = parser.createAST(null);
干杯! 阿育
我沒有在我面前一個正在運行的程序,但基於您鏈接到上面,並在Eclipse的源代碼的文件上,看來,你可以得到CompilationUnit
為ASTNode
通過調用getRoot()
並將其鑄造CompilationUnit
。 另外,從ASTParser
javadoc和ibm的示例中可以ASTParser.createAST(IProgressMonitor)
, ASTParser.createAST(IProgressMonitor)
幾乎總是返回一個CompilationUnit
,它表示您正在解析的源。
在擁有一個名為root
的CompilationUnit
之后,您應該能夠使用root.getLineNumber(node.getStartPosition())
和root.getColumnNumber(node.getStartPosition())
方法。
final ASTParser p = ASTParser.newParser(AST.JLS3);
p.setSource(source);
final CompilationUnit root = (CompilationUnit) p.createAST(null);
// stuff happens
final ASTNode node = //get a node
final int line = root.getLineNumber(node.getStartPosition());
final int column = root.getColumnNumber(node.getStartPosition());
System.out.println("Node started at (" + line + ", " + column + ")";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.