void (final PsiFile file, @NotNull final PsiElement resolved, final String referenceName, final PsiClass resolvedClass) { file.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceElement(@NotNull PsiJavaCodeReferenceElement reference) { super.visitReferenceElement(reference); if (referenceName != null && referenceName.equals(reference.getReferenceName())) { PsiElement resolved = reference.resolve(); if (resolved != null) { reference.putUserData(TEMP_REFERENT_USER_DATA, resolved); } } } }); PsiImportStatementBase existingImport = findExistingImport(file, resolvedClass, referenceName); if (existingImport == null && resolved instanceof PsiClass) { ((PsiImportHolder) file).importClass((PsiClass) resolved); } else if (existingImport == null || existingImport.isOnDemand() && resolvedClass != null && ImportHelper.hasConflictingOnDemandImport((PsiJavaFile)file, resolvedClass, referenceName)) { PsiReferenceExpressionImpl.bindToElementViaStaticImport(resolvedClass, referenceName, ((PsiJavaFile)file).getImportList()); } file.accept(new JavaRecursiveElementVisitor() { @Override public void visitImportList(@NotNull PsiImportList list) { } @Override public void visitReferenceElement(@NotNull PsiJavaCodeReferenceElement reference) { try { if (checkParameterizedReference(reference)) return; if (referenceName.equals(reference.getReferenceName()) && !(reference instanceof PsiMethodReferenceExpression)) { final PsiElement qualifierExpression = reference.getQualifier(); PsiElement referent = reference.getUserData(TEMP_REFERENT_USER_DATA); if (!reference.isQualified()) { if (referent instanceof PsiMember && referent != reference.resolve()) { try { final PsiClass containingClass = ((PsiMember)referent).getContainingClass(); if (containingClass != null) { reference = rebind(reference, containingClass); } } catch (IncorrectOperationException e) { LOG.error (e); } } } else if (referent == null || referent instanceof PsiClass || referent instanceof PsiMember && ((PsiMember)referent).hasModifierProperty(PsiModifier.STATIC)) { if (qualifierExpression instanceof PsiJavaCodeReferenceElement) { PsiElement aClass = ((PsiJavaCodeReferenceElement)qualifierExpression).resolve(); if (aClass instanceof PsiVariable) { aClass = PsiUtil.resolveClassInClassTypeOnly(((PsiVariable)aClass).getType()); } if (aClass instanceof PsiClass && InheritanceUtil.isInheritorOrSelf((PsiClass)aClass, resolvedClass, true)) { try { new CommentTracker().deleteAndRestoreComments(qualifierExpression); } catch (IncorrectOperationException e) { LOG.error(e); } if (referent == null ? reference.resolve() != null : !referent.isEquivalentTo(reference.resolve())) { reference = rebind(reference, resolvedClass); } } } } reference.putUserData(TEMP_REFERENT_USER_DATA, null); } } finally { super.visitReferenceElement(reference); } } }); }