简体   繁体   English

如何使用javaparser获取二进制子表达式

[英]How to get binary subexpressions with javaparser

I am using javaparser to parse the AST for Java source files. 我正在使用javaparser解析Java源文件的AST。

I would like to get all binary subexpressions in the source code as individual nodes. 我想将源代码中的所有二进制子表达式作为单个节点获取。 Here is the source code I am parsing: 这是我正在解析的源代码:

class MyClass {
  public MyClass() {
    double x = (4 / 10.0) + 15;
  }
}

I implemented a Visitor that accepts the built-in BinaryExp type, but the only node that it finds contains the binary expression: 我实现了一个Visitor,该Visitor接受内置的BinaryExp类型,但是它找到的唯一节点包含二进制表达式:

(4 / 10.0) + 15

Is there a way to visit the subexpression "(4 / 10.0)" as well? 有没有办法访问子表达式“(4 / 10.0)”? I tried getting the full expression's "left operand", but it is of type Expression, and not BinaryExpr as I expected. 我尝试获取完整表达式的“左操作数”,但是它的类型为Expression,而不是我期望的BinaryExpr。

Any help would be appreciated. 任何帮助,将不胜感激。

The left operand cannot be of actual type Expression because Expression is an abstract class. 左操作数不能为Expression的实际类型,因为Expression是抽象类。

  • You can check the actual type by checking binEx.getLeft() instanceof BinaryExp .If this evaluates true, you can cast to BinaryExpression. 您可以通过检查binEx.getLeft() instanceof BinaryExp检查实际类型。如果该值为true,则可以binEx.getLeft() instanceof BinaryExp为BinaryExpression。
  • But probably it evaluates false and the node is of type EnclosedExpr (parentheses). 但是可能它的计算结果为false,并且该节点的类型为EnclosedExpr (括号)。 Then the binary expression is the child of the left node 那么二进制表达式是左节点的子代

This will probably not solve the whole problem. 这可能无法解决整个问题。 I think you missed to apply the visitor to the child nodes. 我认为您错过了将访问者应用于子节点。 You have to adjust visit(BinaryExpr n, A arg) : 您必须调整visit(BinaryExpr n, A arg)

  • if you use a GenericVisitorAdaptor you will have to call super.visit(n,arg) 如果您使用GenericVisitorAdaptor ,则必须调用super.visit(n,arg)
  • if you wrote your own adaptor you will have to call accept(this, arg) on each child. 如果您编写了自己的适配器,则必须在每个子代上调用accept(this, arg)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM