PsiJavaFile (@NotNull PsiElement elementBeforeName) { PsiElement parent = elementBeforeName.getParent(); if (parent == null) return null; PsiElement grandParent = parent.getParent(); if (grandParent == null) return null; if (grandParent instanceof PsiJavaFile f) { return f; } PsiElement grandGrandParent = grandParent.getParent(); if (grandGrandParent == null) return null; return ObjectUtils.tryCast(grandGrandParent.getParent(), PsiJavaFile.class); }