我正在使用JavaParser库来解析Java代码并访问Java代码令牌。
以下是我的代码
import java.util.Vector;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;
public class MethodParser {
public static void main(String[] args) throws Exception {
// creates an input stream for the file to be parsed
FileInputStream in = new FileInputStream("F:\\Projects\\Parse.java");
CompilationUnit cu;
try {
// parse the file
cu = JavaParser.parse(in);
} finally {
in.close();
}
cu.accept(new MethodVisitor(), null);
}
private static class MethodVisitor extends VoidVisitorAdapter<Void> {
@Override
public void visit(MethodDeclaration n, Void arg) {
/* here you can access the attributes of the method.
this method will be called for all methods in this
CompilationUnit, including inner class methods */
String x =String.valueOf(n.getBody() );
n.ifAssertStmt(n);
System.out.println(x);
super.visit(n, arg);
}
public void visitVariables(MethodDeclaration n, Void arg) {
String x =String.valueOf(n.getBody());
System.out.println(x);
super.visit(n, arg);
}
}
}
以下是JavaParser(Parse.java)读取的Java文件的代码
public class Parse{
public void printFirstName(){
System.out.println("My First name is John");
}
public void printLastName(){
System.out.println("My Last name is John");
}
public static void main(String[] args){
Parse A = new Parse();
A.printFirstName();
}
}
输出打印parse.java类中所有方法主体的内容。但是我想获取在主方法中调用的方法(在这种情况下,即printFirstName),该怎么办?
答案 0 :(得分:1)
我会使用访客并: 1)在visitMethodDeclaration中设置一个标志,以检查您正在访问的方法是否是主方法(名称,静态标志,参数类型) 2)在visitMethodCallExpression方法中,仅当设置了第1点的标志时,我才会打印呼叫