Effective way to scan the project for specific annotation
Hi, I would like to know how to get references to the methods that are annotated with a specific annotation and having specific annotation text. It could be in a jar or a directory.
eg
@CustomAnnotation("search term")
public void run() {
}
I was thinking about getting all the java files using FilenameIndex, but isn't there a better way to do this.
final Collection<VirtualFile> files = FilenameIndex.getAllFilesByExt(project, "java", GlobalSearchScope.allScope(project));
But this seems to search files in the jdk also. Is there a way to add filters to the search.
请先登录再写评论。
Use com.intellij.psi.search.searches.AnnotatedElementsSearch#searchPsiMethods to search all annotated PsiMethods in a given scope (e.g. module(s), project production scope). Then filter results according to annotation parameter values.
I used AnnotatedElementsSearch.searchPsiMethods like you had mentioned but it just returns me an empty collection. I'm not sure what I'm doing wron here. I just have a single class in my src directory with a few methods annotated with CustomAnnotation.
final PsiManagerEx instance = (PsiManagerEx) PsiManagerEx.getInstance(element.getProject());
final PsiElementFactoryImpl psiElementFactory = new PsiElementFactoryImpl(instance);
final PsiClass stepClass = psiElementFactory.createAnnotationType("CustomAnnotation");
final Query<PsiMethod> psiMethods = AnnotatedElementsSearch.searchPsiMethods(stepClass, GlobalSearchScope.allScope(element.getProject()));
final Collection<PsiMethod> all = psiMethods.findAll();
I was looking into idea's codebase on how AnnotatedElementsSearch.searchPsiMethods is used but I couldn't seem to find any usages in the project.
Please try using com.intellij.psi.JavaPsiFacade#findClass to pass in "annotationClass" parameter to com.intellij.psi.search.searches.AnnotatedElementsSearch#searchPsiMethods
Hi,
you could also try something like:
And then go trough the collection and search for the "search term".
Thanks Yann, got it working now.