Im trying to use Eclipse JDT to go from a parameter of a method to its constructing method (in case its an Object).
I need the MethodDeclaration ASTNode (because I may have to dive in deeper recursively if there is an object parameter again in the declaration).
Its quite the same action like highlighting a type in Eclipse and press F3. So I guess its possible to do this.
Before I was trying to find the method by name and parameters by looping through all of the parsed CompilationUnits of the package. But that seems to be quite expansive? (And resolving + getDeclaringMethod only gave me IMethodBinding, wich is something different and not very effective to cast into a MethodDeclaration?)
Isn't there a more direct way to get from a Type-Node to the MethodDeclaration-Node of its constructor event if it is not in the same CompilationUnit?
You need to retrieve the ICompilationUnit from the binding, parse it and then find the corresponding MethodDeclaration
. The code could look something like this:
IType declaringType = (IType)methodBinding.getDeclaringClass().getJavaElement();
IMethod methodDeclaration = (IMethod)methodBinding.getMethodDeclaration().getJavaElement();
ICompilationUnit declaringUnit = declaringType.getCompilationUnit();
CompilationUnit unit = parseAST(declaringUnit);
unit.accept(new ASTVisitor() {
@Override
public boolean visit(MethodDeclaration node) {
IMethod method = (IMethod)node.resolveBinding().getJavaElement();
if (method.equals(methodDeclaration)) {
...
}
return false;
}
});