PsiElement (PsiField variable, Collection<? extends PsiReferenceExpression> references) { Project project = variable.getProject(); final PsiCodeBlock anchorBlock = findAnchorBlock(references); if (anchorBlock == null) return null; // was assertion, but need to fix the case when obsolete inspection highlighting is left final PsiElement firstElement = getLowestOffsetElement(references); final String localName = suggestLocalName(project, variable, anchorBlock); if (firstElement == null) return null; final PsiElement anchor = getAnchorElement(anchorBlock, firstElement); if (anchor == null) return null; final PsiAssignmentExpression anchorAssignmentExpression = searchAssignmentExpression(anchor); final PsiExpression initializer; if (anchorAssignmentExpression != null && isVariableAssignment(anchorAssignmentExpression, variable)) { initializer = anchorAssignmentExpression.getRExpression(); } else { initializer = variable.getInitializer(); } final PsiElementFactory psiFactory = JavaPsiFacade.getElementFactory(variable.getProject()); final PsiDeclarationStatement declaration = psiFactory.createVariableDeclarationStatement(localName, variable.getType(), initializer); if (ContainerUtil.exists(references, PsiUtil::isAccessedForWriting)) { PsiUtil.setModifierProperty((PsiLocalVariable)declaration.getDeclaredElements()[0], PsiModifier.FINAL, false); } final PsiElement newDeclaration; if (anchorAssignmentExpression != null && isVariableAssignment(anchorAssignmentExpression, variable)) { newDeclaration = new CommentTracker().replaceAndRestoreComments(anchor, declaration); } else if (anchorBlock.getParent() instanceof PsiSwitchStatement) { PsiElement parent = anchorBlock.getParent(); PsiElement switchContainer = parent.getParent(); newDeclaration = switchContainer.addBefore(declaration, parent); } else { newDeclaration = anchorBlock.addBefore(declaration, anchor); } retargetReferences(psiFactory, localName, references); return newDeclaration; }