public static void replaceReference(@NotNull String className, @NotNull PsiJavaCodeReferenceElement ref) throws IncorrectOperationException {
    final Project project = ref.getProject();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final PsiElementFactory factory = facade.getElementFactory();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);

    final PsiElement insertedElement;
    final PsiElement parent = ref.getParent();
    if (parent instanceof PsiReferenceExpression) {
      final PsiClass aClass = facade.findClass(className, scope);
      if (aClass == null) return;
      ((PsiReferenceExpression)parent).setQualifierExpression(factory.createReferenceExpression(aClass));
      insertedElement = ((PsiReferenceExpression)parent).getQualifierExpression();
      assert insertedElement != null : parent;
    }
    else {
      final PsiJavaCodeReferenceElement newReference = factory.createReferenceElementByFQClassName(className, scope);
      insertedElement = ref.replace(newReference);
    }
    final PsiElement shortenedElement = JavaCodeStyleManager.getInstance(project).shortenClassReferences(insertedElement);
    CodeStyleManager.getInstance(project).reformat(shortenedElement);
  }
public static void replaceReference(@NotNull String className, @NotNull PsiJavaCodeReferenceElement ref)