Search code examples
javaparsingjavaparser

Javaparser - How to read a method if a condition occurs


I'm using JavaParser library and I would like how to do this: I want to parse a method and If there is a RestTemplate call, I want to get the "url" value. This is my method:

    public void myMethod() {
        try {
            String url = "http://www.google.com";
            ResponseEntity<String> response = restTemplate
                    .exchange(url, HttpMethod.GET, HttpEntity.EMPTY, String.class);
                    
        } catch (Exception exception) {
            //Error
        }
    }

So I want to extract the value of "url" but only if I find a restTemplate call before. In other words that it also serves me, I need the "url" value of the restTemplate call.

What I'm doing now is:

I assume that Url variable has a constant value, like: url = "google.com". So I want to read a MethodCallExpr that contains an "exchange" word, then I want to read the first param of the method (in this case, the param is "url") so I need to go "backward" to read the value of url, in this case "google.com". What I'm doing now is: Set an ArrayList with all class VariableDeclarators. Then read MethodCallExpr that contains RestTemplate. And finally, extract the first param of the method to get the value from the ArrayList. That's work but It's not very fancy.

But I want to know If there is a way to read "backwards" and remove my ArrayList that contains all class VariableDeclarations.


Solution

  • "But I want to know If there is a way to read "backwards" and remove my ArrayList that contains all class VariableDeclarations."

    No need to read backwards. Once you get the parameter you can resolve it with symbol solver to obtain the declaration. At this stage if you want to analyze the AST you can use getWrapped method on the declaration. Below a simple example

    CompilationUnit cu = StaticJavaParser.parse(code);
    List<MethodCallExpr> methodCallExpr = cu.findAll(MethodCallExpr.class);
    for (MethodCallExpr expr : methodCallExpr) {
        Expression arg = expr.getArgument(0);
        // test if it's a NameExpr
        ResolvedValueDeclaration vd = arg.asNameExpr().resolve();
        if (vd.isField()) {
            FieldDeclaration vde = ((JavaParserFieldDeclaration)vd).getWrappedNode();
            System.out.println(vde.getVariable(0).getInitializer().get());
        }
    }