Can't get method overrides correctly
Answered
I'm trying to get method overrides if any present. I do the following:
PsiMethod myMethod = psiClass.findMethodsByName("myMethod", true).findFirst().orElse(null);
Collection<PsiMethod> overrides = OverridingMethodsSearch.search(myMethod, psiClass.getUseScope(), false).findAll();
The problem is that overrides also contains methods from different classes of the same java file. I'm checking it by the calling of
override.getContainingClass().
How should I define the search scope to consider only specified class methods?
Please sign in to leave a comment.
Could you please post some sample code where wrong results are generated?
Hi, the scenario I used is the following.
I had a class:
public class TestClass {
public static void main(String[] args) {
Set<TestClass> aSet = new HashSet<>();
}
public static class TestClass2 {
@Override
public int hashCode() {
return ...;
}
}
}
Then I get psiType for the HashSet, and getting psiClass by calling
After that, I'm getting the hashCode method
PsiMethod hashCode = psiClass.findMethodsByName("hashCode", true)[0]and call OverridingMethodsSearch.search()
As a result, I'm getting the method from the TestClass2, but psiClass is for TestClass1.
Just wanted to know what is wrong in my code.
Thanks!
Hi,
1. `psiClass.findMethodsByName(name, true)` searches for all methods in the `psiClass` hierarchy, including `java.lang.Object` and I would not rely on the order of methods here. In your case it looks like you don't have explicit hashCode in your class (`TestClass`) thus one from Object is picked
2. overriding methods search will search for all explicit methods which overrides given method in the scope. In your case, you get one from `TestClass2` as nothing else is found in your project (at least I suppose so from your sample).
3. `psiClass.getUseScope()` would return scope where the class can be used. For public production classes (without jigsaw constraints) - everywhere in your project. If you want to narrow down the scope, you may use `LocalSearchScope(psiClass)` but if you would call `psiClass.findMethodsByName(name, false)` then you get exactly the same results, no?
Hope, this helps
Anna
Hi Anna,
Thanks for your response! It makes sense.