PsiMethod containing PsiReference
To community,
I'm stuck into constructing PsiElement calls chain and deleting the chain at once.
I found out that
PsiReference.getElement().delete();
delets just a reference itself, and then I need an actual PsiElement(PsiMethod in most cases) which contains that reference.
For example in the following situation, to delete foo and fooCaller at once is what I'm working on.
public void foo() { /* do something */ }
public void fooCaller() {
foo(); // PsiReference of foo() refers here
}
=======================================
PsiMethod fooElement = // PsiMethod of foo
ArrayList<PsiReference> references = new ArrayList<>(ReferencesSearch.search(fooElement).findAll());
PsiElement fooCallerElement = references.get(0).getElement();
/* It doesn't delete fooCaller! */
fooCallerElement.delete();
Please sign in to leave a comment.
So you want to delete the whole method containing the reference, right? Even if it contains other code?
You can traverse the PSI hierarchy up using PsiElement#getParent. You can find the nearest containing PsiMethod by using PsiTreeUtil#getParentOfType, and delete it. Please note that there might be several containing methods, if anonymous or local classes are involved;
Sorry, I don't understand what you want. Could you please provide code samples showing the reference and the element you want to delete?
@Peter Sorry, I should've described in detail.I edited my post :)
Peter, that's what I exactly need! Thanks you so much :)
I think you meant PsiTreeUtil, btw.
Right, thanks!