Javaparser: Visit methods and apply visitors inside the methods

Created on 19 Feb 2017  路  4Comments  路  Source: javaparser/javaparser

Hi there,

Great work on the parser! Loving it!

I am designing a neural net that has something to do with Logging. For that, I need to identify methods and find out if the methods contain statements that comply with some rules.

For eg., I need to find if the methods contain any switch blocks, any for loops and so on, which the parser does with ease if I supply a file.

I need to know if there is a way to visit each file to get the methods(I used MethodDeclaration), and then apply other visitors to those methods (such as SwitchStmt, and so on). I wrote two GenericVisitorAdapters, the first one is a MethodDeclaration and other is a SwitchStmt. The SwitchStmt visitor doesn't seem to be called.
Visitors.txt

Question (JP usage)

All 4 comments

Hi, thanks for the compliment!

Here's a quick reply that which goes through all classes inside the compilation unit, then goes through all its methods, then runs your visitor to find a switch. Note that a visitor is used by calling accept on a node, not by calling visit on the visitor. You may want to give the book a quick read (there's not much in there yet, but it does deal with visitors)

public class Issue778 {
    public static void main(String[] args) {
        CompilationUnit cu = JavaParser.parse("class X {void x (){switch (1){}}}");
        cu.getTypes().forEach(type ->
                type.getMethods().forEach(method -> {
                            method.accept(new GenericVisitorAdapter<Node, Void>() {
                                @Override
                                public Node visit(SwitchStmt n, Void arg) {
                                    System.out.println("Found a switch inside the method");
                                    return n;
                                }
                            }, null);
                        }
                )
        );
    }
}

Oh, and it looks like you're using an outdated version of JavaParser!

@kmdee6 - did this solve your problem? If so, can you close the issue?

Oops.. Doin now!
It did solve my problem, thanks a lot guys.. Cheers! :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nerzid picture nerzid  路  4Comments

matozoid picture matozoid  路  5Comments

NicoN777 picture NicoN777  路  5Comments

shibumi picture shibumi  路  4Comments

rdurelli picture rdurelli  路  5Comments