How to go from one of IBinding, IJavaElement, ASTNode to another?
From an IBinding to its declaring ASTNode
org.eclipse.jdt.core.dom.CompilationUnit.findDeclaringNode(IBinding)
From an IBinding to an IJavaElement
org.eclipse.jdt.core.dom.IBinding.getJavaElement()
From an ASTNode to an IBinding
Look for a 'resolveBinding()' (or similarly named method) method in a subtype of ASTNode. Note that not all subtypes of ASTNode have a corresponding binding, e.g. MethodDeclaration, Expression and VariableDeclaration have one but IfStatement and ForStatement do not.
From an IJavaElement to an IBinding
If you only need the binding key and not the binding object itself, look for a 'getKey()' method in a subtype of IJavaElement. This method returns the binding key, which can be useful in many situations e.g. see next point. Note that not all subtypes of IJavaElement have a corresponding binding, e.g. IType and IMethod have one but IPackageFragment and IImportContainer do not.
If you really need the binding objects you can use 'org.eclipse.jdt.core.dom.ASTParser.createBindings(IJavaElement[], IProgressMonitor)'. Note that this operation is slightly expensive, compared to just getting the binding key, as the bindings have to be created.
From an IJavaElement to its declaring ASTNode
org.eclipse.jdt.core.dom.CompilationUnit.findDeclaringNode(String) - The string parameter is the binding key, see previous point.
说明:有前同事问到jdt与ast的转化,今天也无意中在JDT的FAQ中看到了上面说明,转帖之。
删减其它聊天刻录:
ast-->jdt
binding.getJavaElement()
jdt-->ast
org.eclipse.jdt.core.dom.CompilationUnit.findDeclaringNode(String)
乘客 10:57:49
public ASTNode findDeclaringNode(String key) {
return this.ast.getBindingResolver().findDeclaringNode(key);
}
key参数你可以传IJavaElement.getkey()进去
乘客 10:59:30
需要设置setResolveBindings(true)