PsiAnnotation (PsiElement element, @Nullable PsiElement stop, @NotNull Set<String> fqAnnotationNames) { while (element != null) { if (element == stop) { return null; } if (element instanceof PsiModifierListOwner modifierListOwner) { final PsiAnnotation annotation = AnnotationUtil.findAnnotationInHierarchy(modifierListOwner, fqAnnotationNames); if (annotation != null) { return annotation; } } if (element instanceof PsiClassOwner classOwner) { final String packageName = classOwner.getPackageName(); final PsiPackage aPackage = JavaPsiFacade.getInstance(element.getProject()).findPackage(packageName); if (aPackage == null) { return null; } final PsiAnnotation annotation = AnnotationUtil.findAnnotation(aPackage, fqAnnotationNames); if(annotation != null) { // Check that annotation actually belongs to the same library/source root // which could be important in case of split-packages final VirtualFile annotationFile = PsiUtilCore.getVirtualFile(annotation); final VirtualFile currentFile = classOwner.getVirtualFile(); if(annotationFile != null && currentFile != null) { final ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(element.getProject()); final VirtualFile annotationClassRoot = projectFileIndex.getClassRootForFile(annotationFile); final VirtualFile currentClassRoot = projectFileIndex.getClassRootForFile(currentFile); if (!Objects.equals(annotationClassRoot, currentClassRoot)) { return null; } } } return annotation; } element = element.getContext(); } return null; }