PsiElement (@NotNull final PsiMember member, @NotNull final PsiClass targetClass, final Set<PsiMember> membersToMove) { if (member instanceof PsiField && member.hasModifierProperty(PsiModifier.STATIC)) { final List<PsiField> afterFields = new ArrayList<>(); final PsiExpression psiExpression = ((PsiField)member).getInitializer(); if (psiExpression != null) { psiExpression.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceExpression(final @NotNull PsiReferenceExpression expression) { super.visitReferenceExpression(expression); final PsiElement psiElement = expression.resolve(); if (psiElement instanceof PsiField psiField && (psiField.getContainingClass() == targetClass || membersToMove.contains(psiField)) && !afterFields.contains(psiField)) { afterFields.add(psiField); } } }); } if (!afterFields.isEmpty()) { afterFields.sort((o1, o2) -> -PsiUtilCore.compareElementsByPosition(o1, o2)); return afterFields.get(0); } final List<PsiField> beforeFields = new ArrayList<>(); for (PsiReference psiReference : ReferencesSearch.search(member, new LocalSearchScope(targetClass))) { final PsiField fieldWithReference = PsiTreeUtil.getParentOfType(psiReference.getElement(), PsiField.class); if (fieldWithReference != null && !afterFields.contains(fieldWithReference) && fieldWithReference.getContainingClass() == targetClass) { beforeFields.add(fieldWithReference); } } beforeFields.sort(PsiUtil.BY_POSITION); if (!beforeFields.isEmpty()) { return beforeFields.get(0).getPrevSibling(); } } return null; }