Skip to content

Instantly share code, notes, and snippets.

@ftomassetti
Created May 27, 2017 09:19
Show Gist options
  • Save ftomassetti/92d5d9527f64ac2957f6a297279b0770 to your computer and use it in GitHub Desktop.
Save ftomassetti/92d5d9527f64ac2957f6a297279b0770 to your computer and use it in GitHub Desktop.
Selecting while statements using a reference as condition
public class FindWhileStatements {
public static void main(String[] args) {
String code = "class A {\n" +
"\tstatic boolean f = true;\n" +
"\tvoid methodFoo() {\n" +
"\t\twhile (f) {\n" +
"\t\t\tmethodFoo();\n" +
"\t\t}\n" +
"\t}\n" +
"}";
new NodeIterator(node -> {
if (node instanceof WhileStmt) {
WhileStmt whileStmt = (WhileStmt)node;
if (whileStmt.getCondition() instanceof NameExpr) {
System.out.println("FOUND!");
}
}
return true;
})
.explore(JavaParser.parse(code));
}
}
package me.tomassetti.support;
import com.github.javaparser.ast.Node;
public class NodeIterator {
public interface NodeHandler {
boolean handle(Node node);
}
private NodeHandler nodeHandler;
public NodeIterator(NodeHandler nodeHandler) {
this.nodeHandler = nodeHandler;
}
public void explore(Node node) {
if (nodeHandler.handle(node)) {
for (Node child : node.getChildNodes()) {
explore(child);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment