Java MethodDeclaration ClassOrInterfaceDeclaration finding class names

1k Views Asked by At

I'm using the MethodDeclaration for a java parser that reads in source code but I'm having some problems. I can't see any methods which give me the class that this belongs to. Does a method exist for this or do I need to look in the java parser to try and create a way that will attach each MethodDeclaration to it's ClassOrInterfaceDeclaration .

I either need a way of detecting if a MethodDeclaration belongs to a class or I need a way of getting all of the methods in a ClassOrInterfaceDeclaration.

edit to make this more clear:

MethodDeclaration m = oldMethodDeclaration ; //where oldMethodDeclaration is already defined method declaration

I need a way to find the class that "m" belongs to. In the following example it will return "ClassName"

ie

    public class ClassName{
public void oldMethodDeclaration (){
}

}

Alternatively if I have

ClassOrInterfaceDeclaration ClassName;

is it possible for me to find a list of method names attached to it?

1

There are 1 best solutions below

0
On

It seems you are using JavaParser.

So to get the enclosing class for a MethodDeclaration:

TypeDeclaration t = (TypeDeclaration) m.getParentNode();

To visit methods of a ClassOrInterfaceDeclaration:

c.accept(new VoidVisitorAdapter<Void>() {
    @Override
    public void visit(MethodDeclaration n, Void arg) {
        System.out.println("Method name: " + n.getName());
    }
}, null);

I just printed the method names. I assume that gives you the necessary information to write a visitor to do something else with the MethodDeclarations.