问题
How can a FieldDeclaration
(type: ASTNode) be converted to an IField
(type: JavaElement). Is it possible to get the binding from the FieldDeclaration ASTNode, just like node.resolveBinding() as for MethodDeclaration node.
Need : I am visiting a FieldDeclaration node in a Class having public constants, and want to search references for that field in the project. I am using JDT's SearchEngine for same. For this I want to create a search pattern as follows :
SearchPattern.createPattern(iField, IJavaSearchConstants.REFERENCES);
I have asked this as a comment to one of my questions, but didn't get the answer for same. Posting it as separate question.
Thanks in advance for the answer.
In reply to Deepak's answer.
Using your approach i can retrieve the JavaElement as follows
List<VariableDeclarationFragment> fragments = node.fragments();
VariableDeclarationFragment fragment = fragments.get(0);
IJavaElement fieldElement = fragment.resolveBinding().getJavaElement();
If i am passing this IJavaElement to create the search pattern instead of the IField will it return the same result as those for an IField.
回答1:
As usual ASTView plugin is your friend! :-) In the ASTView you can see that binding is available for VariableDeclarationFragment but not for a FieldDeclaration.
Getting the binding from FieldDeclaration
- Get the 'fragments' of the FieldDeclaration => you now have a bunch of VariableDeclarationFragment nodes
- Call VariableDeclarationFragment#resolveBinding() (this method is inherited from VariableDeclaration)
来源:https://stackoverflow.com/questions/11131793/fielddeclaration-to-ifield-getting-ibinding-from-fielddeclaration