PsiElement (final Map<PsiVariable, PsiElement> elementsToReplace, PsiElement expression) { final Map<PsiElement, PsiElement> replacements = new HashMap<>(); expression.accept(new JavaRecursiveElementVisitor() { @Override public void visitReferenceExpression(@NotNull PsiReferenceExpression referenceExpression) { super.visitReferenceExpression(referenceExpression); final PsiElement resolved = referenceExpression.resolve(); if (resolved instanceof PsiVariable variable) { final PsiElement replacement = elementsToReplace.get(variable); if (replacement != null) { replacements.put(referenceExpression, replacement); } } } }); return CommonJavaRefactoringUtil.replaceElementsWithMap(expression, replacements); }