コード例 #1
0
 public MoveInstanceMethodProcessor(
     final Project project,
     final PsiMethod method,
     final PsiVariable targetVariable,
     final String newVisibility,
     final Map<PsiClass, String> oldClassParameterNames) {
   super(project);
   myMethod = method;
   myTargetVariable = targetVariable;
   myOldClassParameterNames = oldClassParameterNames;
   LOG.assertTrue(
       myTargetVariable instanceof PsiParameter || myTargetVariable instanceof PsiField);
   LOG.assertTrue(myTargetVariable.getType() instanceof PsiClassType);
   final PsiType type = myTargetVariable.getType();
   LOG.assertTrue(type instanceof PsiClassType);
   myTargetClass = ((PsiClassType) type).resolve();
   myNewVisibility = newVisibility;
 }
 private void copyToFinal() throws IncorrectOperationException {
   PsiManager psiManager = myClass.getManager();
   PsiElementFactory factory =
       JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
   PsiExpression initializer = factory.createExpressionFromText(myVariable.getName(), myClass);
   String newName = suggestNewName(psiManager.getProject(), myVariable);
   PsiType type = myVariable.getType();
   PsiDeclarationStatement copyDecl =
       factory.createVariableDeclarationStatement(newName, type, initializer);
   PsiVariable newVariable = (PsiVariable) copyDecl.getDeclaredElements()[0];
   PsiUtil.setModifierProperty(newVariable, PsiModifier.FINAL, true);
   PsiElement statement = getStatementToInsertBefore();
   if (statement == null) return;
   statement.getParent().addBefore(copyDecl, statement);
   PsiExpression newExpression = factory.createExpressionFromText(newName, myVariable);
   replaceReferences(myClass, myVariable, newExpression);
 }
コード例 #3
0
  protected void performRefactoring(UsageInfo[] usages) {
    if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myTargetClass)) return;

    PsiMethod patternMethod = createMethodToAdd();
    final List<PsiReference> docRefs = new ArrayList<PsiReference>();
    for (UsageInfo usage : usages) {
      if (usage instanceof InheritorUsageInfo) {
        final PsiClass inheritor = ((InheritorUsageInfo) usage).getInheritor();
        addMethodToClass(inheritor, patternMethod, true);
      } else if (usage instanceof MethodCallUsageInfo
          && !((MethodCallUsageInfo) usage).isInternal()) {
        final PsiElement expression = ((MethodCallUsageInfo) usage).getMethodCallExpression();
        if (expression instanceof PsiMethodCallExpression) {
          correctMethodCall((PsiMethodCallExpression) expression, false);
        } else if (expression instanceof PsiMethodReferenceExpression) {
          PsiExpression newQualifier =
              JavaPsiFacade.getInstance(myProject)
                  .getElementFactory()
                  .createExpressionFromText(myTargetVariable.getType().getCanonicalText(), null);
          ((PsiMethodReferenceExpression) expression).setQualifierExpression(newQualifier);
        }
      } else if (usage instanceof JavadocUsageInfo) {
        docRefs.add(usage.getElement().getReference());
      }
    }

    try {
      if (myTargetClass.isInterface()) patternMethod.getBody().delete();

      final PsiMethod method = addMethodToClass(myTargetClass, patternMethod, false);
      myMethod.delete();
      for (PsiReference reference : docRefs) {
        reference.bindToElement(method);
      }
      VisibilityUtil.fixVisibility(UsageViewUtil.toElements(usages), method, myNewVisibility);

      if (myOpenInEditor) {
        EditorHelper.openInEditor(method);
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
 private static String getUniqueParameterName(
     PsiParameter[] parameters, PsiVariable variable, HashMap<PsiField, String> usedNames) {
   final JavaCodeStyleManager styleManager =
       JavaCodeStyleManager.getInstance(variable.getProject());
   final SuggestedNameInfo nameInfo =
       styleManager.suggestVariableName(
           VariableKind.PARAMETER,
           styleManager.variableNameToPropertyName(variable.getName(), VariableKind.FIELD),
           null,
           variable.getType());
   String newName = nameInfo.names[0];
   int n = 1;
   while (true) {
     if (isUnique(parameters, newName, usedNames)) {
       break;
     }
     newName = nameInfo.names[0] + n++;
   }
   return newName;
 }
コード例 #5
0
  public static Set<String> suggestExpressionOfType(
      final PsiClassType type, final PsiLiteralExpression context) {
    PsiVariable[] variables = MacroUtil.getVariablesVisibleAt(context, "");
    Set<String> result = new LinkedHashSet<String>();
    for (PsiVariable var : variables) {
      PsiType varType = var.getType();
      if (type == null || type.isAssignableFrom(varType)) {
        result.add(var.getNameIdentifier().getText());
      }
    }

    PsiExpression[] expressions = MacroUtil.getStandardExpressionsOfType(context, type);
    for (PsiExpression expression : expressions) {
      result.add(expression.getText());
    }
    if (type != null) {
      addAvailableMethodsOfType(type, context, result);
    }
    return result;
  }
  private void makeArray(PsiVariable variable) throws IncorrectOperationException {
    PsiType type = variable.getType();

    PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory();
    PsiType newType = type.createArrayType();

    PsiDeclarationStatement variableDeclarationStatement;
    PsiExpression initializer = variable.getInitializer();
    if (initializer == null) {
      String expression = "[1]";
      while (type instanceof PsiArrayType) {
        expression += "[1]";
        type = ((PsiArrayType) type).getComponentType();
      }
      PsiExpression init =
          factory.createExpressionFromText("new " + type.getCanonicalText() + expression, variable);
      variableDeclarationStatement =
          factory.createVariableDeclarationStatement(variable.getName(), newType, init);
    } else {
      PsiExpression init =
          factory.createExpressionFromText("{ " + initializer.getText() + " }", variable);
      variableDeclarationStatement =
          factory.createVariableDeclarationStatement(variable.getName(), newType, init);
    }
    PsiVariable newVariable = (PsiVariable) variableDeclarationStatement.getDeclaredElements()[0];
    PsiUtil.setModifierProperty(newVariable, PsiModifier.FINAL, true);
    PsiElement newExpression =
        factory.createExpressionFromText(variable.getName() + "[0]", variable);

    PsiElement outerCodeBlock = PsiUtil.getVariableCodeBlock(variable, null);
    if (outerCodeBlock == null) return;
    List<PsiReferenceExpression> outerReferences = new ArrayList<PsiReferenceExpression>();
    collectReferences(outerCodeBlock, variable, outerReferences);
    replaceReferences(outerReferences, newExpression);
    variable.replace(newVariable);
  }
  private static boolean addParameterToConstructor(
      final Project project,
      final PsiFile file,
      final Editor editor,
      final PsiMethod constructor,
      final PsiField[] fields)
      throws IncorrectOperationException {
    final PsiParameterList parameterList = constructor.getParameterList();
    final PsiParameter[] parameters = parameterList.getParameters();
    ParameterInfoImpl[] newParamInfos = new ParameterInfoImpl[parameters.length + fields.length];
    final List<PsiVariable> params = new ArrayList<PsiVariable>(Arrays.asList(parameters));
    Collections.addAll(params, fields);
    Collections.sort(params, new FieldParameterComparator(parameterList));

    int i = 0;
    final HashMap<PsiField, String> usedFields = new HashMap<PsiField, String>();
    for (PsiVariable param : params) {
      final PsiType paramType = param.getType();
      if (param instanceof PsiParameter) {
        newParamInfos[i++] =
            new ParameterInfoImpl(
                parameterList.getParameterIndex((PsiParameter) param),
                param.getName(),
                paramType,
                param.getName());
      } else {
        final String uniqueParameterName = getUniqueParameterName(parameters, param, usedFields);
        usedFields.put((PsiField) param, uniqueParameterName);
        newParamInfos[i++] =
            new ParameterInfoImpl(-1, uniqueParameterName, paramType, uniqueParameterName);
      }
    }
    final SmartPointerManager manager = SmartPointerManager.getInstance(project);
    final SmartPsiElementPointer constructorPointer =
        manager.createSmartPsiElementPointer(constructor);

    final PsiMethod fromText =
        JavaPsiFacade.getElementFactory(project)
            .createMethodFromText(createDummyMethod(constructor, newParamInfos), constructor);
    final PsiClass containingClass = constructor.getContainingClass();
    if (containingClass == null) return false;
    final int minUsagesNumber =
        containingClass.findMethodsBySignature(fromText, false).length > 0 ? 0 : 1;
    final List<ParameterInfoImpl> parameterInfos =
        ChangeMethodSignatureFromUsageFix.performChange(
            project, editor, file, constructor, minUsagesNumber, newParamInfos, true, true);

    final ParameterInfoImpl[] resultParams =
        parameterInfos != null
            ? parameterInfos.toArray(new ParameterInfoImpl[parameterInfos.size()])
            : newParamInfos;
    return ApplicationManager.getApplication()
        .runWriteAction(
            new Computable<Boolean>() {
              @Override
              public Boolean compute() {
                return doCreate(
                    project, editor, parameters, constructorPointer, resultParams, usedFields);
              }
            });
  }