首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Compiler解析if else语句

使用Compiler解析if else语句
EN

Stack Overflow用户
提问于 2015-03-26 15:06:29
回答 1查看 687关注 0票数 0

我正试图找到一种使用Tree解析netbeans中的java代码源代码的方法,我通过这个指南学习了如何访问高级语言元素(类、方法、字段.)。

我要寻找的是一种解析if way语句的方法(首先),因为之后我尝试用状态策略重构来应用替换类型代码。对我来说,获得条件是非常重要的。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-02 14:24:06

在深入研究Compiler文档之后,我发现了如何访问低级别代码--在我的例子中,这是一个选中的if语句的条件,下面是一个代码片段

代码语言:javascript
复制
  @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进行调试对于了解接下来要处理的树是非常有用的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29281945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档