int (PsiVariable enumerationVariable, int startOffset, String newVariableName) { final PsiManager manager = enumerationVariable.getManager(); final Project project = manager.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final PsiElementFactory factory = facade.getElementFactory(); final Query<PsiReference> query = ReferencesSearch.search( enumerationVariable); final List<PsiElement> referenceElements = new ArrayList<>(); for (PsiReference reference : query) { final PsiElement referenceElement = reference.getElement(); referenceElements.add(referenceElement); } referenceElements.sort(PsiElementOrderComparator.getInstance()); int result = KEEP_NOTHING; for (PsiElement referenceElement : referenceElements) { if (!(referenceElement instanceof PsiReferenceExpression referenceExpression)) { result = KEEP_DECLARATION; continue; } if (referenceElement.getTextOffset() <= startOffset) { result = KEEP_DECLARATION; continue; } final PsiElement referenceParent = referenceExpression.getParent(); if (!(referenceParent instanceof PsiReferenceExpression)) { if (referenceParent instanceof PsiAssignmentExpression) { result = KEEP_DECLARATION; break; } result = KEEP_INITIALIZATION; continue; } final PsiElement referenceGrandParent = referenceParent.getParent(); if (!(referenceGrandParent instanceof PsiMethodCallExpression callExpression)) { result = KEEP_INITIALIZATION; continue; } final PsiReferenceExpression foundReferenceExpression = callExpression.getMethodExpression(); @NonNls final String foundName = foundReferenceExpression.getReferenceName(); @NonNls final String newExpressionText; if ("hasMoreElements".equals(foundName)) { newExpressionText = newVariableName + ".hasNext()"; } else if ("nextElement".equals(foundName)) { newExpressionText = newVariableName + ".next()"; } else { result = KEEP_INITIALIZATION; continue; } final PsiExpression newExpression = factory.createExpressionFromText(newExpressionText, callExpression); callExpression.replace(newExpression); } return result; }