How to convert from JavaElement to its ASTNode declaration?

I read this article from the Wiki Eclipse (http://wiki.eclipse.org/JDT/FAQ#From_an_IJavaElement_to_its_declaring_ASTNode), but I still cannot convert from IMethod to its corresponding Methodology.

I have an extension point that adds a popup menu to IMethod objects. With this IMethod, I want to visit it with ASTVisitor.

This is how I try to convert from IMethod to MethodDeclaration

public static MethodDeclaration convertToAstNode(final IMethod method) throws JavaModelException { final ICompilationUnit compilationUnit = method.getCompilationUnit(); final ASTParser astParser = ASTParser.newParser( AST.JLS4 ); astParser.setSource( compilationUnit ); astParser.setKind( ASTParser.K_COMPILATION_UNIT ); astParser.setResolveBindings( true ); astParser.setBindingsRecovery( true ); final ASTNode rootNode = astParser.createAST( null ); final CompilationUnit compilationUnitNode = (CompilationUnit) rootNode; final String key = method.getKey(); final ASTNode javaElement = compilationUnitNode.findDeclaringNode( key ); final MethodDeclaration methodDeclarationNode = (MethodDeclaration) javaElement; return methodDeclarationNode; } 

What am I missing?

+4
source share
1 answer

I understand that this question is quite old, but I want to publish this solution in case future googlers accidentally stumble upon it :)

The EijiAdachi workaround posted in the comments should work, but there is a more β€œcorrect” way to do this, which I found while searching for a solution.

In order for ASTNode to correctly resolve bindings, you first need to fully analyze the contents of the page. This is done using the method (somewhat strangely called IMHO) ASTNode.accept(ASTVisitor) . Therefore, if you subclass ASTVisitor, you can override visiting methods for all types of ASTNode that you are interested in and add them to the data structures available after a full AST analysis.

In this example, all MethodDeclaration nodes will be available in the root directory of the CompilationUnit node (see the OP for this via the ASTParser class):

 public class MethodVisitor extends ASTVisitor { private final List <MethodDeclaration> methods = new ArrayList <> (); @Override public boolean visit (final MethodDeclaration method) { methods.add (method); return super.visit (method); } /** * @return an immutable list view of the methods discovered by this visitor */ public List <MethodDeclaration> getMethods () { return Collections.unmodifiableList (methods); } } 

Any of the other ASTNode subtypes can be rounded using the same process (you can create separate types of visitors or put all of this into one).

If anyone is interested, you can find a more complete example in this article .

+1
source

Source: https://habr.com/ru/post/1434983/


All Articles