如何使用javaparser获取在类的方法内部使用的变量名

时间:2020-10-28 12:34:37

标签: java javaparser

我正在分析的课程:

public class Users{
    private String name = "Jacob";
    private String address = "711 11th Ave, New York";
    private int age = 28;
    
    public String verifyAgeLimit() {
        String msg = (this.age < 16) ? " is not allwed to use it." : " is Allwed to use it.";   
        return this.name+msg;
    }
    
    public String showName() {
        return "User name is:"+this.name;
    }
    
    public String showAddress() {
        return this.address;
    }

    public String hello() {
        return "Hello World";
    }
}

我正在尝试使用MethodDeclaration获取变量名,但无法做到这一点。

public void visit(MethodDeclaration n, Object arg) {        
   System.out.println(n.getName().toString());//It displays the full method
   super.visit(n, arg);
}

我正试图为此输出。

verifyAgeLimit() this.name name

verifyAgeLimit() this.name name

showAddress()此地址地址

我试图将整个方法转换为字符串,然后读取字符串以查找名称,但是它变得过于复杂且准确性下降。

有什么办法解决吗?

1 个答案:

答案 0 :(得分:0)

已使用变量的名称由NameExpr节点保存,而字段由FieldAccessExpr节点保存。为他们添加访问者,否则递归到他们。

相关问题