我正试图找到一种使用Tree解析netbeans中的java代码源代码的方法,我通过这个指南学习了如何访问高级语言元素(类、方法、字段.)。
我要寻找的是一种解析if way语句的方法(首先),因为之后我尝试用状态策略重构来应用替换类型代码。对我来说,获得条件是非常重要的。任何帮助都将不胜感激。
发布于 2015-04-02 14:24:06
在深入研究Compiler文档之后,我发现了如何访问低级别代码--在我的例子中,这是一个选中的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进行调试对于了解接下来要处理的树是非常有用的。
https://stackoverflow.com/questions/29281945
复制相似问题