how to get reference method for class in intellj plugin

Answered

I want to develop an IntelliJ plugin I have two classes

public class A { public void sum() {}}
public class B extends a{ }

my question is how to search the references(usages) of sum method in class B without including the usages in class A

I am using ReferencesSearch#search but it gets the method usages in class A and class B

8 comments
Comment actions Permalink

You can't (directly). However, you can filter them out programmatically like this: `ReferenceSearch.search(element).forEach(ref -> { if (!isInside(ref, classB)) handle(ref); })`. 

where 

```

boolean isInside(PsiReference ref, PsiElement aClass) {

return PsiTreeUtil.isAncestor(aClass, ref.getElement(), false);

}

```

0
Comment actions Permalink

it does not work in this case 


public class A { public void sum() {}}
public class B extends A{ }
public class D extends A{ }

it returns the usage of  the sum method in D class
I need the method usages for a specific class 

0
Comment actions Permalink

If you need usages from your specific class only, please try

<code>ReferenceSearch.search(element).forEach(ref -> { if (isInside(ref, yourSpecificClass)) handle(ref); return true; })</code>

0
Comment actions Permalink

it didn't return a result, the result should be the method usages for class B only 
can you check

0
Comment actions Permalink

No, ReferenceSearch.search(element).forEach() doesn't return the result, it passes the found usages to the processor instead, where you can store the usages to the collection, for example.

E.g.

{code}

List<PsiReference> usagesInClassA = new ArrayList<>();

ReferenceSearch.search(element).forEach(ref -> { if (isInside(ref, classA)) usagesInClassA.add(ref); return true; })

{code}

0
Comment actions Permalink

it does not work 
please refer to 

public Collection<PsiReference> searchMethod(PsiMethod method, PsiClass aClass) {
List<PsiReference> psiReferences = new ArrayList<>();
ReferencesSearch.search(method, GlobalSearchScope.projectScope(project), true).forEach(new Consumer<PsiReference>() {
@Override
public void accept(PsiReference psiReference) {
if (isInside(psiReference, aClass)) {
psiReferences.add(psiReference);
}
}
});

return psiReferences;
}
0
Comment actions Permalink

Excellent, I'm glad you've figured it out.

-1
Comment actions Permalink

I meant it doesn't work it return an empty result  

0

Please sign in to leave a comment.