Created
May 27, 2017 09:19
-
-
Save ftomassetti/92d5d9527f64ac2957f6a297279b0770 to your computer and use it in GitHub Desktop.
Selecting while statements using a reference as condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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