Search code examples
eclipse-jdt

How to get ASTNode definition in JDT?


I can get IBinding from a MethodInvocation.getName() and now I want to get the offset of this binding in the CompilationUnit in order to get the definition position. But I can not find any information of this. By the way, I use ASTParser.setSource(char[]) not IJavaProject.


Solution

  • The normal approach in JDT looks like this:

    IJavaElement method= methodBinding.getJavaElement();
    if (method instanceof IMember) {
        ICompilationUnit cu= ((IMember) method).getCompilationUnit();
        CompilationUnit compilationUnit= // use ASTParser here...
        ASTNode methodDecl= compilationUnit.findDeclaringNode(methodBinding.getKey());
        ... methodDecl.getStartPosition() ...
    }
    

    This, however, requires that the Java Model is available. If you don't have an IJavaProject then #getJavaElement() will probably answer null. In that case you will have to implement your own heuristic for mapping an ITypeBinding (from IMethodBinding#getDeclaringClass()) to a compilation unit.

    Put differently: if you want JDT to help locating elements outside the current compilation unit, then using the Java Model is the way to go.

    As an alternative to using the full-blown Java Model, you could try parsing all relevant compilation units in one batch (using #getASTs() - plural), and then create your own reverse map from ITypeBinding to CompilationUnit.