PsiElement (@NotNull PsiJavaFile clsFile) { Function<VirtualFile, VirtualFile> finder = null; Predicate<PsiFile> filter = null; PsiClass[] classes = clsFile.getClasses(); if (classes.length > 0) { String sourceFileName = ((ClsClassImpl)classes[0]).getSourceFileName(); String packageName = clsFile.getPackageName(); String relativePath = packageName.isEmpty() ? sourceFileName : packageName.replace('.', '/') + '/' + sourceFileName; finder = root -> root.findFileByRelativePath(relativePath); filter = PsiClassOwner.class::isInstance; } else { PsiJavaModule module = clsFile.getModuleDeclaration(); if (module != null) { String moduleName = module.getName(); finder = root -> !JrtFileSystem.isModuleRoot(root) || moduleName.equals(root.getName()) ? root.findChild(PsiJavaModule.MODULE_INFO_FILE) : null; filter = psi -> { PsiJavaModule candidate = psi instanceof PsiJavaFile ? ((PsiJavaFile)psi).getModuleDeclaration() : null; return candidate != null && moduleName.equals(candidate.getName()); }; } } if (finder == null) return clsFile; return findSourceRoots(clsFile.getContainingFile().getVirtualFile()) .map(finder) .filter(source -> source != null && source.isValid()) .map(PsiManager.getInstance(myProject)::findFile) .filter(filter) .findFirst() .orElse(clsFile); }