private void addParameters(
     final PsiElementFactory factory, final PsiMethod methodCopy, final boolean isInterface)
     throws IncorrectOperationException {
   final Set<Map.Entry<PsiClass, String>> entries = myOldClassParameterNames.entrySet();
   for (final Map.Entry<PsiClass, String> entry : entries) {
     final PsiClassType type = factory.createType(entry.getKey());
     final PsiParameter parameter = factory.createParameter(entry.getValue(), type);
     if (isInterface) {
       PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, false);
     }
     methodCopy.getParameterList().add(parameter);
   }
 }
 private String getParameterNameToCreate(@NotNull PsiClass aClass) {
   return myOldClassParameterNames.get(aClass);
 }
  private PsiMethod createMethodToAdd() {
    ChangeContextUtil.encodeContextInfo(myMethod, true);
    try {
      final PsiManager manager = myMethod.getManager();
      final PsiElementFactory factory =
          JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();

      // correct internal references
      final PsiCodeBlock body = myMethod.getBody();
      if (body != null) {
        final Map<PsiElement, PsiElement> replaceMap = new HashMap<PsiElement, PsiElement>();
        body.accept(
            new JavaRecursiveElementVisitor() {
              @Override
              public void visitThisExpression(PsiThisExpression expression) {
                final PsiClass classReferencedByThis =
                    MoveInstanceMembersUtil.getClassReferencedByThis(expression);
                if (classReferencedByThis != null
                    && !PsiTreeUtil.isAncestor(myMethod, classReferencedByThis, false)) {
                  final PsiElementFactory factory =
                      JavaPsiFacade.getInstance(myProject).getElementFactory();
                  String paramName = getParameterNameToCreate(classReferencedByThis);
                  try {
                    final PsiExpression refExpression =
                        factory.createExpressionFromText(paramName, null);
                    replaceMap.put(expression, refExpression);
                  } catch (IncorrectOperationException e) {
                    LOG.error(e);
                  }
                }
              }

              @Override
              public void visitReferenceExpression(PsiReferenceExpression expression) {
                try {
                  final PsiExpression qualifier = expression.getQualifierExpression();
                  final PsiElement resolved = expression.resolve();
                  if (qualifier instanceof PsiReferenceExpression
                      && ((PsiReferenceExpression) qualifier).isReferenceTo(myTargetVariable)) {
                    if (resolved instanceof PsiField) {
                      for (PsiParameter parameter : myMethod.getParameterList().getParameters()) {
                        if (Comparing.strEqual(
                            parameter.getName(), ((PsiField) resolved).getName())) {
                          qualifier.replace(factory.createExpressionFromText("this", null));
                          return;
                        }
                      }
                    }
                    // Target is a field, replace target.m -> m
                    qualifier.delete();
                    return;
                  }
                  if (myTargetVariable.equals(resolved)) {
                    PsiThisExpression thisExpression =
                        RefactoringChangeUtil.createThisExpression(
                            manager,
                            PsiTreeUtil.isAncestor(
                                    myMethod,
                                    PsiTreeUtil.getParentOfType(expression, PsiClass.class),
                                    true)
                                ? myTargetClass
                                : null);
                    replaceMap.put(expression, thisExpression);
                    return;
                  } else if (myMethod.equals(resolved)) {
                  } else {
                    PsiClass classReferencedByThis =
                        MoveInstanceMembersUtil.getClassReferencedByThis(expression);
                    if (classReferencedByThis != null) {
                      final String paramName = getParameterNameToCreate(classReferencedByThis);
                      if (paramName != null) {
                        PsiReferenceExpression newQualifier =
                            (PsiReferenceExpression)
                                factory.createExpressionFromText(paramName, null);
                        expression.setQualifierExpression(newQualifier);
                        return;
                      }
                    }
                  }
                  super.visitReferenceExpression(expression);
                } catch (IncorrectOperationException e) {
                  LOG.error(e);
                }
              }

              @Override
              public void visitNewExpression(PsiNewExpression expression) {
                try {
                  final PsiExpression qualifier = expression.getQualifier();
                  if (qualifier instanceof PsiReferenceExpression
                      && ((PsiReferenceExpression) qualifier).isReferenceTo(myTargetVariable)) {
                    // Target is a field, replace target.new A() -> new A()
                    qualifier.delete();
                  } else {
                    final PsiClass classReferencedByThis =
                        MoveInstanceMembersUtil.getClassReferencedByThis(expression);
                    if (classReferencedByThis != null) {
                      if (qualifier != null) qualifier.delete();
                      final String paramName = getParameterNameToCreate(classReferencedByThis);
                      final PsiExpression newExpression =
                          factory.createExpressionFromText(
                              paramName + "." + expression.getText(), null);
                      replaceMap.put(expression, newExpression);
                    }
                  }
                  super.visitNewExpression(expression);
                } catch (IncorrectOperationException e) {
                  LOG.error(e);
                }
              }

              @Override
              public void visitMethodCallExpression(PsiMethodCallExpression expression) {
                correctMethodCall(expression, true);
                super.visitMethodCallExpression(expression);
              }
            });
        for (PsiElement element : replaceMap.keySet()) {
          final PsiElement replacement = replaceMap.get(element);
          element.replace(replacement);
        }
      }

      final PsiMethod methodCopy = getPatternMethod();

      final List<PsiParameter> newParameters =
          Arrays.asList(methodCopy.getParameterList().getParameters());
      RefactoringUtil.fixJavadocsForParams(methodCopy, new HashSet<PsiParameter>(newParameters));
      return methodCopy;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return myMethod;
    }
  }
  private void correctMethodCall(
      final PsiMethodCallExpression expression, final boolean isInternalCall) {
    try {
      final PsiManager manager = myMethod.getManager();
      PsiReferenceExpression methodExpression = expression.getMethodExpression();
      if (!methodExpression.isReferenceTo(myMethod)) return;
      final PsiExpression oldQualifier = methodExpression.getQualifierExpression();
      PsiExpression newQualifier = null;
      final PsiClass classReferencedByThis =
          MoveInstanceMembersUtil.getClassReferencedByThis(methodExpression);
      if (myTargetVariable instanceof PsiParameter) {
        final int index =
            myMethod.getParameterList().getParameterIndex((PsiParameter) myTargetVariable);
        final PsiExpression[] arguments = expression.getArgumentList().getExpressions();
        if (index < arguments.length) {
          newQualifier = (PsiExpression) arguments[index].copy();
          arguments[index].delete();
        }
      } else {
        VisibilityUtil.escalateVisibility((PsiField) myTargetVariable, expression);
        String newQualifierName = myTargetVariable.getName();
        if (myTargetVariable instanceof PsiField && oldQualifier != null) {
          final PsiClass aClass = PsiUtil.resolveClassInClassTypeOnly(oldQualifier.getType());
          if (aClass == ((PsiField) myTargetVariable).getContainingClass()) {
            newQualifierName = oldQualifier.getText() + "." + newQualifierName;
          }
        }
        newQualifier =
            JavaPsiFacade.getInstance(manager.getProject())
                .getElementFactory()
                .createExpressionFromText(newQualifierName, null);
      }

      PsiExpression newArgument = null;

      if (classReferencedByThis != null) {
        @NonNls String thisArgumentText = null;
        if (manager.areElementsEquivalent(myMethod.getContainingClass(), classReferencedByThis)) {
          if (myOldClassParameterNames.containsKey(myMethod.getContainingClass())) {
            thisArgumentText = "this";
          }
        } else {
          thisArgumentText = classReferencedByThis.getName() + ".this";
        }

        if (thisArgumentText != null) {
          newArgument =
              JavaPsiFacade.getInstance(manager.getProject())
                  .getElementFactory()
                  .createExpressionFromText(thisArgumentText, null);
        }
      } else {
        if (!isInternalCall && oldQualifier != null) {
          final PsiType type = oldQualifier.getType();
          if (type instanceof PsiClassType) {
            final PsiClass resolved = ((PsiClassType) type).resolve();
            if (resolved != null && getParameterNameToCreate(resolved) != null) {
              newArgument =
                  replaceRefsToTargetVariable(
                      oldQualifier); // replace is needed in case old qualifier is e.g. the same as
                                     // field as target variable
            }
          }
        }
      }

      if (newArgument != null) {
        expression.getArgumentList().add(newArgument);
      }

      if (newQualifier != null) {
        if (newQualifier instanceof PsiThisExpression
            && ((PsiThisExpression) newQualifier).getQualifier() == null) {
          // Remove now redundant 'this' qualifier
          if (oldQualifier != null) oldQualifier.delete();
        } else {
          final PsiReferenceExpression refExpr =
              (PsiReferenceExpression)
                  JavaPsiFacade.getInstance(manager.getProject())
                      .getElementFactory()
                      .createExpressionFromText("q." + myMethod.getName(), null);
          refExpr.getQualifierExpression().replace(newQualifier);
          methodExpression.replace(refExpr);
        }
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }