我想使用java解析器解析check()方法。使用getStatements()方法在MethodDeclaration中可以得到该方法。但是我想遍历方法中的代码。有没有办法这么做。我需要计算这个方法中返回语句的数量。
final JavaParser javaParser = new JavaParser();
final CompilationUnit compilationUnit = pr.getResult().get();
final TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);
MethodDeclaration md = (MethodDeclaration) resourceClass.getMethodsByName("check");
md.getBody().get().getStatements();
private int check(){
if(x=y)
return 10;
else
return 5;
}发布于 2022-07-30 23:10:34
您需要定义一个计算ReturnStmt实例的访问者。这样做的一种方法是:
class ReturnStmtCounter extends GenericVisitorWithDefaults<Integer, Void> {
public int countReturnStmts(Node n) {
return n.accept(this, null);
}
public Integer defaultAction(NodeList<?> n, Void arg) {
return sumReturnStmts(n, arg);
}
public Integer defaultAction(Node n, Void arg) {
return sumReturnStmts(n.getChildNodes(), arg);
}
@Override
public Integer visit(ReturnStmt returnStmt, Void arg) {
return 1;
}
private int sumReturnStmts(Collection<? extends Node> nodes, Void arg) {
return nodes.stream().mapToInt(n -> n.accept(this, null)).sum();
}
}备注
countReturnStmts接受可能位于ASTReturnStmt实例,则停止并返回1.G 211
https://stackoverflow.com/questions/72448491
复制相似问题