Example #1
0
  public static PsiMethod generateSetterPrototype(
      PsiField field, final PsiClass containingClass, boolean returnSelf) {
    Project project = field.getProject();
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();

    String name = field.getName();
    boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
    VariableKind kind = codeStyleManager.getVariableKind(field);
    String propertyName = codeStyleManager.variableNameToPropertyName(name, kind);
    String setName = suggestSetterName(project, field);
    try {
      PsiMethod setMethod =
          factory.createMethod(
              setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID);
      String parameterName =
          codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
      PsiParameter param = factory.createParameter(parameterName, field.getType());

      annotateWithNullableStuff(field, factory, param);

      setMethod.getParameterList().add(param);
      PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true);
      PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic);

      @NonNls StringBuffer buffer = new StringBuffer();
      buffer.append("{\n");
      if (name.equals(parameterName)) {
        if (!isStatic) {
          buffer.append("this.");
        } else {
          String className = containingClass.getName();
          if (className != null) {
            buffer.append(className);
            buffer.append(".");
          }
        }
      }
      buffer.append(name);
      buffer.append("=");
      buffer.append(parameterName);
      buffer.append(";\n");
      if (returnSelf) {
        buffer.append("return this;\n");
      }
      buffer.append("}");
      PsiCodeBlock body = factory.createCodeBlockFromText(buffer.toString(), null);
      setMethod.getBody().replace(body);
      setMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(setMethod);
      return setMethod;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  private static PsiAnnotationMemberValue[] readFromClass(
      @NonNls String attributeName, @NotNull PsiAnnotation magic, PsiType type) {
    PsiAnnotationMemberValue fromClassAttr = magic.findAttributeValue(attributeName);
    PsiType fromClassType =
        fromClassAttr instanceof PsiClassObjectAccessExpression
            ? ((PsiClassObjectAccessExpression) fromClassAttr).getOperand().getType()
            : null;
    PsiClass fromClass =
        fromClassType instanceof PsiClassType ? ((PsiClassType) fromClassType).resolve() : null;
    if (fromClass == null) return null;
    String fqn = fromClass.getQualifiedName();
    if (fqn == null) return null;
    List<PsiAnnotationMemberValue> constants = new ArrayList<PsiAnnotationMemberValue>();
    for (PsiField field : fromClass.getFields()) {
      if (!field.hasModifierProperty(PsiModifier.PUBLIC)
          || !field.hasModifierProperty(PsiModifier.STATIC)
          || !field.hasModifierProperty(PsiModifier.FINAL)) continue;
      PsiType fieldType = field.getType();
      if (!Comparing.equal(fieldType, type)) continue;
      PsiAssignmentExpression e =
          (PsiAssignmentExpression)
              JavaPsiFacade.getElementFactory(field.getProject())
                  .createExpressionFromText("x=" + fqn + "." + field.getName(), field);
      PsiReferenceExpression refToField = (PsiReferenceExpression) e.getRExpression();
      constants.add(refToField);
    }
    if (constants.isEmpty()) return null;

    return constants.toArray(new PsiAnnotationMemberValue[constants.size()]);
  }
 private static PsiField convertFieldToLanguage(PsiField field, Language language) {
   if (field.getLanguage().equals(language)) {
     return field;
   }
   return JVMElementFactories.getFactory(language, field.getProject())
       .createField(field.getName(), field.getType());
 }
 public CreateConstructorParameterFromFieldFix(@NotNull PsiField field) {
   myClass = field.getContainingClass();
   myField =
       SmartPointerManager.getInstance(field.getProject()).createSmartPsiElementPointer(field);
   if (myClass != null) {
     getFieldsToFix().add(myField);
   }
 }
 private static void notNull(Project project, PsiField field, PsiParameter parameter) {
   final String notNull = NullableNotNullManager.getInstance(field.getProject()).getNotNull(field);
   if (notNull != null) {
     final PsiAnnotation annotation =
         JavaPsiFacade.getElementFactory(project).createAnnotationFromText("@" + notNull, field);
     parameter.getModifierList().addBefore(annotation, null);
   }
 }
 public RemoveMiddlemanProcessor(PsiField field, List<MemberInfo> memberInfos) {
   super(field.getProject());
   this.field = field;
   containingClass = field.getContainingClass();
   final String propertyName = PropertyUtil.suggestPropertyName(field);
   final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
   getter = PropertyUtil.findPropertyGetter(containingClass, propertyName, isStatic, false);
   myDelegateMethodInfos = memberInfos;
 }
Example #7
0
  public static PsiMethod generateGetterPrototype(PsiField field) {
    PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();
    Project project = field.getProject();
    String name = field.getName();
    String getName = suggestGetterName(project, field);
    try {
      PsiMethod getMethod = factory.createMethod(getName, field.getType());
      PsiUtil.setModifierProperty(getMethod, PsiModifier.PUBLIC, true);
      if (field.hasModifierProperty(PsiModifier.STATIC)) {
        PsiUtil.setModifierProperty(getMethod, PsiModifier.STATIC, true);
      }

      annotateWithNullableStuff(field, factory, getMethod);

      PsiCodeBlock body = factory.createCodeBlockFromText("{\nreturn " + name + ";\n}", null);
      getMethod.getBody().replace(body);
      getMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(getMethod);
      return getMethod;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  private PsiMethod generateMethodPrototype(PsiField field) {
    Project project = field.getProject();
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();

    String propertyName =
        codeStyleManager.variableNameToPropertyName(
            field.getName(), codeStyleManager.getVariableKind(field));
    String methodName = methodNameGenerator.generateMethodNameFor(propertyName);
    String parameterName =
        codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);

    PsiMethod withMethod = generateMethodFor(field, methodName, parameterName, elementFactory);
    generateMethodBodyFor(withMethod, propertyName, parameterName, elementFactory);

    return withMethod;
  }
Example #9
0
 public void run() {
   final ReadonlyStatusHandler roHandler = ReadonlyStatusHandler.getInstance(myField.getProject());
   final PsiFile psiFile = myField.getContainingFile();
   if (psiFile == null) return;
   final ReadonlyStatusHandler.OperationStatus status =
       roHandler.ensureFilesWritable(psiFile.getVirtualFile());
   if (status.hasReadonlyFiles()) return;
   ApplicationManager.getApplication()
       .runWriteAction(
           new Runnable() {
             public void run() {
               CommandProcessor.getInstance()
                   .executeCommand(
                       myField.getProject(),
                       new Runnable() {
                         public void run() {
                           try {
                             final PsiManager manager = myField.getManager();
                             myField
                                 .getTypeElement()
                                 .replace(
                                     JavaPsiFacade.getInstance(manager.getProject())
                                         .getElementFactory()
                                         .createTypeElement(myNewType));
                           } catch (final IncorrectOperationException e) {
                             ApplicationManager.getApplication()
                                 .invokeLater(
                                     new Runnable() {
                                       public void run() {
                                         Messages.showErrorDialog(
                                             myEditor,
                                             UIDesignerBundle.message(
                                                 "error.cannot.change.field.type",
                                                 myField.getName(),
                                                 e.getMessage()),
                                             CommonBundle.getErrorTitle());
                                       }
                                     });
                           }
                         }
                       },
                       getName(),
                       null);
             }
           });
 }
  /**
   * Create a new {@link FieldElement} object.
   *
   * @param field the {@link com.intellij.psi.PsiField} to get the information from.
   * @return a new {@link FieldElement} object.
   */
  public static FieldElement newFieldElement(PsiField field, boolean useAccessor) {
    FieldElement fe = new FieldElement();
    fe.setName(field.getName());
    final PsiMethod getterForField = useAccessor ? PropertyUtil.findGetterForField(field) : null;
    fe.setAccessor(getterForField != null ? getterForField.getName() + "()" : field.getName());

    if (PsiAdapter.isConstantField(field)) fe.setConstant(true);
    if (PsiAdapter.isEnumField(field)) fe.setEnum(true);
    PsiModifierList modifiers = field.getModifierList();
    if (modifiers != null) {
      if (modifiers.hasModifierProperty(PsiModifier.TRANSIENT)) fe.setModifierTransient(true);
      if (modifiers.hasModifierProperty(PsiModifier.VOLATILE)) fe.setModifierVolatile(true);
    }

    PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();
    PsiType type = field.getType();
    setElementInfo(fe, factory, type, modifiers);

    return fe;
  }
  private static String resolveEpName(PsiField psiField) {
    final PsiExpression initializer = psiField.getInitializer();

    PsiExpressionList expressionList = null;
    if (initializer instanceof PsiMethodCallExpression) {
      expressionList = ((PsiMethodCallExpression) initializer).getArgumentList();
    } else if (initializer instanceof PsiNewExpression) {
      expressionList = ((PsiNewExpression) initializer).getArgumentList();
    }
    if (expressionList == null) return null;

    final PsiExpression[] expressions = expressionList.getExpressions();
    if (expressions.length != 1) return null;

    final PsiExpression epNameExpression = expressions[0];
    final PsiConstantEvaluationHelper helper =
        JavaPsiFacade.getInstance(psiField.getProject()).getConstantEvaluationHelper();
    final Object o = helper.computeConstantExpression(epNameExpression);
    return o instanceof String ? (String) o : null;
  }
  public static PsiMethod generateConstructorPrototype(
      PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields)
      throws IncorrectOperationException {
    PsiManager manager = aClass.getManager();
    JVMElementFactory factory =
        JVMElementFactories.requireFactory(aClass.getLanguage(), aClass.getProject());
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());

    PsiMethod constructor = factory.createConstructor(aClass.getName(), aClass);
    String modifier = PsiUtil.getMaximumModifierForMember(aClass, false);

    if (modifier != null) {
      PsiUtil.setModifierProperty(constructor, modifier, true);
    }

    if (baseConstructor != null) {
      PsiJavaCodeReferenceElement[] throwRefs =
          baseConstructor.getThrowsList().getReferenceElements();
      for (PsiJavaCodeReferenceElement ref : throwRefs) {
        constructor.getThrowsList().add(ref);
      }

      if (copyJavaDoc) {
        final PsiDocComment docComment =
            ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment();
        if (docComment != null) {
          constructor.addAfter(docComment, null);
        }
      }
    }

    boolean isNotEnum = false;
    if (baseConstructor != null) {
      PsiClass superClass = aClass.getSuperClass();
      LOG.assertTrue(superClass != null);
      if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) {
        isNotEnum = true;
        if (baseConstructor instanceof PsiCompiledElement) { // to get some parameter names
          PsiClass dummyClass =
              JVMElementFactories.requireFactory(
                      baseConstructor.getLanguage(), baseConstructor.getProject())
                  .createClass("Dummy");
          baseConstructor = (PsiMethod) dummyClass.add(baseConstructor);
        }
        PsiParameter[] params = baseConstructor.getParameterList().getParameters();
        for (PsiParameter param : params) {
          PsiParameter newParam = factory.createParameter(param.getName(), param.getType(), aClass);
          GenerateMembersUtil.copyOrReplaceModifierList(param, newParam);
          constructor.getParameterList().add(newParam);
        }
      }
    }

    JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(aClass.getProject());

    final PsiMethod dummyConstructor = factory.createConstructor(aClass.getName());
    dummyConstructor.getParameterList().replace(constructor.getParameterList().copy());
    List<PsiParameter> fieldParams = new ArrayList<PsiParameter>();
    for (PsiField field : fields) {
      String fieldName = field.getName();
      String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD);
      String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER);
      parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true);
      PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass);

      final NullableNotNullManager nullableManager =
          NullableNotNullManager.getInstance(field.getProject());
      final String notNull = nullableManager.getNotNull(field);
      if (notNull != null) {
        parm.getModifierList()
            .addAfter(factory.createAnnotationFromText("@" + notNull, field), null);
      }

      constructor.getParameterList().add(parm);
      dummyConstructor.getParameterList().add(parm.copy());
      fieldParams.add(parm);
    }

    ConstructorBodyGenerator generator =
        ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage());
    if (generator != null) {
      @NonNls StringBuilder buffer = new StringBuilder();
      generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY);
      if (isNotEnum) {
        generator.generateSuperCallIfNeeded(
            buffer, baseConstructor.getParameterList().getParameters());
      }
      generator.generateFieldInitialization(
          buffer, fields, fieldParams.toArray(new PsiParameter[fieldParams.size()]));
      generator.finish(buffer);
      PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass);
      constructor.getBody().replace(stub.getBody());
    }

    constructor = (PsiMethod) codeStyleManager.reformat(constructor);
    return constructor;
  }
  private static void prepareFieldRenaming(
      PsiField field, String newName, final Map<PsiElement, String> allRenames) {
    // search for getters/setters
    PsiClass aClass = field.getContainingClass();

    Project project = field.getProject();
    final JavaCodeStyleManager manager = JavaCodeStyleManager.getInstance(project);

    final String propertyName = PropertyUtil.suggestPropertyName(field, field.getName());
    final String newPropertyName = PropertyUtil.suggestPropertyName(field, newName);

    boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);

    PsiMethod[] getters = GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic);

    PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false);

    boolean shouldRenameSetterParameter = false;

    if (setter != null) {
      shouldRenameSetterParameter = shouldRenameSetterParameter(manager, propertyName, setter);
    }

    if (getters != null) {
      List<PsiMethod> validGetters = new ArrayList<>();
      for (PsiMethod getter : getters) {
        String newGetterName =
            GetterSetterPrototypeProvider.suggestNewGetterName(
                propertyName, newPropertyName, getter);
        String getterId = null;
        if (newGetterName == null) {
          getterId = getter.getName();
          newGetterName =
              PropertyUtil.suggestGetterName(newPropertyName, field.getType(), getterId);
        }
        if (newGetterName.equals(getterId)) {
          continue;
        } else {
          boolean valid = true;
          for (PsiMethod method : getter.findDeepestSuperMethods()) {
            if (method instanceof PsiCompiledElement) {
              valid = false;
              break;
            }
          }
          if (!valid) continue;
        }
        validGetters.add(getter);
      }
      getters =
          validGetters.isEmpty() ? null : validGetters.toArray(new PsiMethod[validGetters.size()]);
    }

    String newSetterName = "";
    if (setter != null) {
      newSetterName = PropertyUtil.suggestSetterName(newPropertyName);
      final String newSetterParameterName =
          manager.propertyNameToVariableName(newPropertyName, VariableKind.PARAMETER);
      if (newSetterName.equals(setter.getName())) {
        setter = null;
        newSetterName = null;
        shouldRenameSetterParameter = false;
      } else if (newSetterParameterName.equals(
          setter.getParameterList().getParameters()[0].getName())) {
        shouldRenameSetterParameter = false;
      } else {
        for (PsiMethod method : setter.findDeepestSuperMethods()) {
          if (method instanceof PsiCompiledElement) {
            setter = null;
            shouldRenameSetterParameter = false;
            break;
          }
        }
      }
    }

    if ((getters != null || setter != null)
        && askToRenameAccesors(getters != null ? getters[0] : null, setter, newName, project)) {
      getters = null;
      setter = null;
      shouldRenameSetterParameter = false;
    }

    if (getters != null) {
      for (PsiMethod getter : getters) {
        String newGetterName =
            GetterSetterPrototypeProvider.suggestNewGetterName(
                propertyName, newPropertyName, getter);
        if (newGetterName == null) {
          newGetterName =
              PropertyUtil.suggestGetterName(newPropertyName, field.getType(), getter.getName());
        }
        addOverriddenAndImplemented(getter, newGetterName, null, propertyName, manager, allRenames);
      }
    }

    if (setter != null) {
      addOverriddenAndImplemented(
          setter,
          newSetterName,
          shouldRenameSetterParameter ? newPropertyName : null,
          propertyName,
          manager,
          allRenames);
    }
  }