Finding usages/references of Java elements
I'm not implementing a custom language, I just need to be able to see references for Java elements. Essentially, I'm grabbing the same data that appears in `Find Usages`.
When I use:
ReferencesSearch.search(method).findAll();
I get a list of references with the correct number of references, but they all return the same method that I put in, even when I resolve those references.
For example, if I had some code that looked like this:
void myMethod() {
// Do stuff
}
void callMyMethod() {
myMethod();
}
And I found references for `myMethod`, I would get `myMethod` in the list of references.
How do I get `callMyMethod` in the list of references? If I did a `Find Usages` search in the IDE, it would give me `callMyMethod`. It would also be great to get the character offset in the code itself for the method call. (so if my example were the entire file, it would give me a character range of 68 to 76), but maybe once I'm pointed in the right direction I can figure that out on my own.
I've tried getting inspiration the actual `Find Usages` code instead, but it seems very tied to the UI and IDE. I need something that has no attachment to the UI, but if there is not an easy way to do it, I will continue to go down that route.
请先登录再写评论。
Hi,
reference search provides references on the method you search, this means that you'll get PsiReference(s) (all of them would be references on `myMethod` == `ref.resolve() == myMethod`) on which you can call `getElement()` to get call sites. Then you can walk psi tree up, e.g. `PsiTreeUtil.getParentOfType` to get counting method or whatever you want to get from the call site.
Anna
Hi,
I'm searching for references of class, not a method but I'm having the same issue: all returned references are of my class, which I'm searching for. Ok, I get the idea that this is a _reference of my class_ somewhere else. What I need from that is merely file name or class which belongs to this file name. I tried different methods from PsiUtils but still stuck. :/
Ok, I figured that out. The key difference is that you need to call getElement() on reference. If you will use resolve() you will always get the original reference. This is not straightforward to understand.