0

The class which I am analyzing:

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";
    }
}

I'm trying to get variable names using MethodDeclaration, but unable to do so.

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

I am trying to get output for this is.

verifyAgeLimit() : this.name or name

verifyAgeLimit() : this.name or name

showAddress() : this.address or address

I tried to convert the whole method to sting and read the string to find out the names but it is getting too much complicated and very less accurate.

Is there any way to solve it?

RajB009
  • 417
  • 2
  • 7
  • 19
  • I use **JP** now, but I'm not really "advanced." I tried this today, I think your `Visitor` is just right, but you then need to add a **Second `Visitor`** to `walk` the method. This right here: [`accept(VoidVisitor...)`](https://javadoc.io/static/com.github.javaparser/javaparser-core/3.16.2/com/github/javaparser/ast/stmt/BlockStmt.html#accept-com.github.javaparser.ast.visitor.VoidVisitor-A-) ***and then*** this method should help... [`walk(...)`](https://javadoc.io/static/com.github.javaparser/javaparser-core/3.16.2/com/github/javaparser/ast/Node.html#walk-java.util.function.Consumer-) . – Y2020-09 Oct 30 '20 at 14:10

1 Answers1

0

The names of used variables are held by NameExpr nodes and fields by FieldAccessExpr nodes. Add a visitor for them, or otherwise recurse down to them.

OrangeDog
  • 36,653
  • 12
  • 122
  • 207