我使用Eclipse AST解析器解析java源代碼,併成功地將局部變量定位爲VariableDeclarationStatement
。問題是我需要變量作爲重構的使用ILocalVariable
。在這種情況下,getJavaElement()
不起作用,因爲Java模型中的局部變量不是。任何想法如何從那裏得到它?從解析VariableDeclarationStatement獲取ILocalVariable
0
A
回答
0
請注意,我沒有嘗試這樣做自己,但看源代碼,以下提到的步驟應該工作:
- 確保ASTParser使用
setResolveBindings(true)
- 獲取所有的創造通過致電
VariableDeclarationStatement.fragments()
致電VariableDeclarationFragments
。 - 對於您感興趣的每個片段,請致電
resolveBinding()
。 - 對於每個綁定,您應該可以調用
getJavaElement()
。
0
這是另一種選擇。自己創建ILocalVariable對象。 org.eclipse.jdt.internal.core.LocalVariable
是內部API(構造函數在3.6和3.7之間變化)。
構造(在Eclipse 3.6)採用下列參數:
public LocalVariable(
JavaElement parent,
String name,
int declarationSourceStart,
int declarationSourceEnd,
int nameStart,
int nameEnd,
String typeSignature,
org.eclipse.jdt.internal.compiler.ast.Annotation[] astAnnotations)
大部分參數應該從VariableDeclarationStatement
是相當簡單的和可用直接。請注意,typeSignature
不是完全限定的名稱,而是從org.eclipse.jdt.core.Signature
生成的類型簽名。
0
IVariableBinding binding = variable.resolveBinding();
if (!binding.isField() && !binding.isEnumConstant() && !binding.isParameter())
{
ILocalVariable local = (ILocalVariable) binding.getJavaElement();
}
1
你可以嘗試以下方法:
手VariableDeclarationStatement variable
已經編程您可以按代碼:
IVariableBinding binding = variable.resolveBinding();
ILocalVariable local = (ILocalVariable) binding.getJavaElement();
0
我遇到同樣的問題,但上面的工作沒有任何的解決方案給我。經過一番研究,我發現了一個解決方案,這對我的作品:
// reconcile corresponding compilation unit
compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);
// parse code and get the elements
IJavaElement[] elements =
((ICodeAssist) compilationUnit).codeSelect(startPos + length, 0);
// if there is an element and its an instance of ILocalVariable.
if (anElements.length > 0 && anElements[0] instanceof ILocalVariable) {
return (ILocalVariable) anElements[0];
}
所以在最後:你需要的起始位置和變量的長度。 (startPos
+ length
)。還有編輯部門,我已經有了。
相關問題
- 1. 如何從VariableDeclarationStatement獲取方法名稱
- 2. 從類「解析」中獲取文本opennlp
- 3. 如何從URL獲取並解析Json?
- 4. 解析雲 - 從URL獲取縮略圖
- 5. 從API獲取數據和解析
- 6. 從網頁獲取RSS並解析它
- 7. 從html解析器中獲取元素
- 8. json從url解析數據獲取nullpointException
- 9. 如何解析從NumericUpDown獲取的值?
- 10. 從解析列獲取數組到UITableView
- 11. 從userList獲取解析對象android
- 12. 獲取對象從循環中解析
- 13. 從BeautifulSoup解析獲取特定值
- 14. 解析HTML獲取元素
- 15. XML解析獲取編號
- 16. 獲取解析會話ID
- 17. 獲取並解析收藏
- 18. 獲取失敗的解析
- 19. 解析HTML獲取響應
- 20. 獲得「不解析」從Prelude.read
- 21. Htmlparser2解析獲取鏈接,然後解析這些鏈接(node.js)
- 22. HTML解析器獲取鏈接文本
- 23. 使iPhone能夠獲取和解析JSON?
- 24. 使用React.js獲取解析錯誤
- 25. JSON解析器獲取圖像
- 26. 在Actionscript中獲取和解析JSON
- 27. 獲取Sass來解析瀏覽器hacker
- 28. XML解析,以獲取描述標籤
- 29. 獲取用戶名的解析用戶
- 30. lxml:解析html,無法獲取節點
已經試過這種方式,但不幸的是'getJavaElement()'返回null爲局部變量 – JIV 2011-03-18 20:06:56