ASTNode的accept()方法做什么?它如何使用ASTVisitor?

时间:2023-01-25 08:55:50

What does the accept method of ASTNode do (The javadoc didn't help too much...) and when will the visit(Expression node) method be called? Here is an example code of how I need to use it:

ASTNode的accept方法做了什么(javadoc没有提供太多帮助…),什么时候调用visit(Expression节点)方法?以下是我如何使用它的示例代码:

final List<Expression> listi = new ArrayList<Expression>();
String stringi = opi.generate(entryContract, true_false_maybe);
// stringi representes an expression, for example "g!=h".
parser.setSource(stringi.toCharArray());
unit = (CompilationUnit) parser.createAST(null); 
ASTNode astRoot = unit.getRoot();
astRoot.accept(new ASTVisitor() {
 public boolean visit(Expression node) {
  listi.add(node);
  return true;
 }
});

Thank you

谢谢你!

1 个解决方案

#1


1  

I guess your Expression class is a subtype of the ASTNode class, and the ASTVisitor class present other visit methods (which surely will be empty), accepting as an argument other ASTNode subclasses.

我猜您的表达式类是ASTNode类的一个子类,而ASTVisitor类提供其他访问方法(肯定是空的),接受其他ASTNode子类作为参数。

It's an implementation of the GoF Visitor Design Pattern (also described at Wikipedia).

它是GoF访问者设计模式的实现(也在Wikipedia中描述)。

The accept method on ASTNode will just invoke the visit method on the visitor implementation, passing itself as parameter for the visit method.

ASTNode上的accept方法将在visitor实现上调用visit方法,将自己作为visit方法的参数传递。

#1


1  

I guess your Expression class is a subtype of the ASTNode class, and the ASTVisitor class present other visit methods (which surely will be empty), accepting as an argument other ASTNode subclasses.

我猜您的表达式类是ASTNode类的一个子类,而ASTVisitor类提供其他访问方法(肯定是空的),接受其他ASTNode子类作为参数。

It's an implementation of the GoF Visitor Design Pattern (also described at Wikipedia).

它是GoF访问者设计模式的实现(也在Wikipedia中描述)。

The accept method on ASTNode will just invoke the visit method on the visitor implementation, passing itself as parameter for the visit method.

ASTNode上的accept方法将在visitor实现上调用visit方法,将自己作为visit方法的参数传递。