Skip to content

HelperVisitor sample

Carsten Hammer edited this page Nov 4, 2021 · 2 revisions

Old way to use visitor

	private boolean handleMethodInvocation(MethodInvocation assignment) {
		System.out.println(assignment);
		return true;
	}

	...
	ASTVisitor astvisitor=new ASTVisitor() {
		@Override
		public boolean visit(MethodInvocation node) {
			return VisitorTest.this.handleMethodInvocation(node);
		}
	};
	cunit1.accept(astvisitor);

New way to use visitor

The central class here is HelperVisitor. Because of some new features, the number of parameters changed.

  1. ReferenceHolder is a working object to hold information that is needed while visiting the nodes in the tree. You can use it to collect information or to share information.
  2. Set<ASTNode> nodesprocessed is to make sure that processing (changing) a node is not done twice. For cleanups/quickfixes you should not apply two different cleanups at the same time to the same node. This data structure is responsible to remember a node has already got a change and is not processed twice.
	private boolean handleMethodInvocation(MethodInvocation assignment, ReferenceHolder<String,NodeFound> holder) {
		System.out.println(assignment);
		return true;
	}
	
	...
	Set<ASTNode> nodesprocessed = null;
	HelperVisitor<ReferenceHolder<String,NodeFound>,String,NodeFound> hv = new HelperVisitor<>(nodesprocessed, new ReferenceHolder<>());
	hv.addMethodInvocation(this::handleMethodInvocation);
	hv.build(cunit1);