[英]Parse if else statement using Compiler Tree API
我正在嘗試找到一種使用Tree API在netbeans中解析Java代碼源的方法,我通過本指南學習了如何訪問高級語言元素(類,方法,字段..)。
我正在尋找的是一種解析else語句(作為開始)的方法,因為我嘗試在事后使用狀態策略重構來應用替換類型代碼 。 獲得if條件對我來說非常重要。 任何幫助將不勝感激。
深入了解Compiler Tree API文檔后,我發現了如何訪問低級代碼(在我的情況下,條件為選擇的if語句),這是一個代碼段
@Override
public Void visitIf(IfTree node, Void p) {
try {
JTextComponent editor = EditorRegistry.lastFocusedComponent();
if (editor.getDocument() == info.getDocument()) {
InputOutput io = IOProvider.getDefault().getIO("Analysis of " + info.getFileObject().getName(),
true);
ExpressionTree exTree = node.getCondition();
if (exTree.getKind() == Tree.Kind.PARENTHESIZED) {
ParenthesizedTree parTree = (ParenthesizedTree) exTree;
BinaryTree conditionTree = (BinaryTree) parTree.getExpression();
ExpressionTree identTree = conditionTree.getLeftOperand();
if (identTree.getKind() == Tree.Kind.IDENTIFIER) {
Name name = ((IdentifierTree) identTree).getName();
io.getOut().println("Hurray, this is the name of the identifier in the left operand: " + name.toString());
}
io.getOut().close();
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return null;
}
值得慶幸的是,代碼命名很直觀,否則文檔沒有太大幫助。 使用println進行調試對於了解接下來要處理的樹非常有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.