Find all usages of a local variable in java (psi)

Answered

Hi,
I used the methods, getReference() and getReferences() of PsiElement, but they won't return any reference for any of the elements. (tested: PsiClass, PsiIdentifier, PsiMethod, PsiField).

Also I tried ReferencesSearch for the PsiIdentifier but I get empty array.

So, what is the proper way to get the usages of a e.g. local variable?

(I want to do some refactoring on the name of variable/class/...)

4 comments
Comment actions Permalink

Hi Mohammad,

To check if an element contains any references, use PsiViewer and check "references" property  for the selected element:
https://plugins.jetbrains.com/docs/intellij/explore-api.html#31-use-internal-mode-and-psiviewer

It will help to understand how the PSI tree is built and which elements provide references, etc.

How do you use ReferencesSearch class? Are you sure that PsiIdentifier is an element that is referenced by references?

0
Comment actions Permalink
public class Main {
public static void main(String[] args) {
int something = 20;
System.out.println(something);
}
}

in the above example, when caret is on `something` declaration, I get the psi element under the caret which will be a PsiIdentifier, then calling getReference() or getReferences() will return null and empty array, also using ReferencesSearch.search(psiIdentifier) will return empty array for `something`.

I also used the plugin 'psi viewer' but there also wasn't any reference for the `something` variable.

0
Comment actions Permalink

Reference is something like a code expression (e.g. identifier) referencing some declaration/definition, so it is usually usage of some variable, not the declaration. Every PSI element which is usage/reference can return PsiReference objects which are objects that know how to resolve() to this PSI element's declaration. It means that PsiElement.getReferences() will not return usages of a given element, but the reference object for itself.

In your example calling getReference()/getReferences() in the "int something = 20;" expression doesn't make sense, because this is the declaration, not a usage/reference. Try to inspect the "System.out.println(something);" expression. You should find references somewhere in the "something" identifier's hierarchy.

Regarding the ReferencesSearch, try to call it on PsiLocalVariable element, like here:
https://github.com/JetBrains/intellij-community/blob/master/java/java-impl-refactorings/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java#L310

0
Comment actions Permalink

thanks a lot! problem solved

0

Please sign in to leave a comment.