EijiAdachi
EijiAdachi

Reputation: 441

In a JDT AST, how to retrieve the MethodDeclaration node from a MethodInvocation node?

I'm implementing an ASTVisitor and when I visit a MethodInvocation node, I would like to access its corresponding MethodDeclaration node. The following example shows what I need:

public boolean visit(MethodInvocation node){
     MethodDeclaration mDeclaration = getMethodDeclaration( node );
}

I know I can visit my whole project first, saving all method declarations in a map. Then, in a second visitor, I can visit the MethodInvocation node and get its corresponding MethodDeclaration from the map produced by the first visitor. But I'd like to access the corresponding MethodDeclaration node without having to visit the whole project more than once. How can I do that? Is it possible?

Upvotes: 1

Views: 1253

Answers (1)

pakat
pakat

Reputation: 286

Find the corresponding compilation unit via binding of the method, parse it to another AST and get the declaration from the tree:

IMethodBinding binding = (IMethodBinding) node.getName().resolveBinding();
ICompilationUnit unit = (ICompilationUnit) binding.getJavaElement().getAncestor( IJavaElement.COMPILATION_UNIT );
if ( unit == null ) {
   // not available, external declaration
}b
ASTParser parser = ASTParser.newParser( AST.JLS8 );
parser.setKind( ASTParser.K_COMPILATION_UNIT );
parser.setSource( unit );
parser.setResolveBindings( true );
CompilationUnit cu = (CompilationUnit) parser.createAST( null );
MethodDeclaration decl = (MethodDeclaration)cu.findDeclaringNode( binding.getKey() );

Of course, this only works when the method is declared in an Eclipse project, not in an external JAR.

The first AST you are traversing needs to have resolved bindings too: ASTParser.setResolveBindings( true ).

Upvotes: 3

Related Questions