使用 Compiler Tree API 解析 if else 语句
Parse if else statement using Compiler Tree API
我正在尝试找到一种方法来使用树 API 解析 netbeans 中的 java 代码源,我通过这个 guide 了解了如何访问高级语言元素( 类、方法、字段..)。
我正在寻找的是一种解析 if else 语句的方法(首先),因为我试图在之后应用用状态策略替换类型代码 重构。获得 if 条件对我来说非常重要。任何帮助将不胜感激。
在深入了解编译器树 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 进行调试对于了解接下来要处理哪种树非常有用。
我正在尝试找到一种方法来使用树 API 解析 netbeans 中的 java 代码源,我通过这个 guide 了解了如何访问高级语言元素( 类、方法、字段..)。
我正在寻找的是一种解析 if else 语句的方法(首先),因为我试图在之后应用用状态策略替换类型代码 重构。获得 if 条件对我来说非常重要。任何帮助将不胜感激。
在深入了解编译器树 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 进行调试对于了解接下来要处理哪种树非常有用。