@Nullable
 private static String getCannotRefactorMessage(PsiMember member) {
   if (member == null) {
     return RefactoringBundle.message("locate.caret.inside.a.method");
   }
   if (member instanceof PsiMethod) {
     if (((PsiMethod) member).isConstructor()) {
       return RefactoringBundle.message("replace.with.method.call.does.not.work.for.constructors");
     }
     final PsiCodeBlock body = ((PsiMethod) member).getBody();
     if (body == null) {
       return RefactoringBundle.message("method.does.not.have.a.body", member.getName());
     }
     final PsiStatement[] statements = body.getStatements();
     if (statements.length == 0) {
       return RefactoringBundle.message("method.has.an.empty.body", member.getName());
     }
   } else if (member instanceof PsiField) {
     final PsiField field = (PsiField) member;
     if (field.getInitializer() == null) {
       return "Field " + member.getName() + " doesn't have initializer";
     }
     final PsiClass containingClass = field.getContainingClass();
     if (!field.hasModifierProperty(PsiModifier.FINAL)
         || !field.hasModifierProperty(PsiModifier.STATIC)
         || containingClass == null
         || containingClass.getQualifiedName() == null) {
       return "Replace Duplicates works with constants only";
     }
   } else {
     return "Caret should be inside method or constant";
   }
   return null;
 }
예제 #2
0
  @NotNull
  public String elementToKotlin(@NotNull PsiElement element) {
    if (element instanceof PsiJavaFile) {
      return fileToFile((PsiJavaFile) element).toKotlin();
    }

    if (element instanceof PsiClass) {
      return classToClass((PsiClass) element).toKotlin();
    }

    if (element instanceof PsiMethod) {
      return methodToFunction((PsiMethod) element).toKotlin();
    }

    if (element instanceof PsiField) {
      PsiField field = (PsiField) element;
      return fieldToField(field, field.getContainingClass()).toKotlin();
    }

    if (element instanceof PsiStatement) {
      return statementToStatement((PsiStatement) element).toKotlin();
    }

    if (element instanceof PsiExpression) {
      return expressionToExpression((PsiExpression) element).toKotlin();
    }

    return "";
  }
  private NecessaryAccessorsVisitor checkNecessaryGettersSetters4SourceClass() {
    final NecessaryAccessorsVisitor visitor =
        new NecessaryAccessorsVisitor() {
          @Override
          protected boolean hasGetterOrSetter(PsiMethod[] getters) {
            for (PsiMethod getter : getters) {
              if (!isInMovedElement(getter)) return true;
            }
            return false;
          }

          @Override
          protected boolean isProhibitedReference(PsiField field) {
            if (fields.contains(field)) {
              return false;
            }
            if (innerClasses.contains(field.getContainingClass())) {
              return false;
            }
            return true;
          }
        };
    for (PsiField field : fields) {
      field.accept(visitor);
    }
    for (PsiMethod method : methods) {
      method.accept(visitor);
    }
    for (PsiClass innerClass : innerClasses) {
      innerClass.accept(visitor);
    }
    return visitor;
  }
예제 #4
0
 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());
 }
  private void generateAccessors() {
    // generate accessors
    myNameToGetter = new HashMap<String, PsiMethod>();
    myNameToSetter = new HashMap<String, PsiMethod>();

    for (FieldDescriptor fieldDescriptor : myFieldDescriptors) {
      final DocCommentPolicy<PsiDocComment> commentPolicy =
          new DocCommentPolicy<PsiDocComment>(myDescriptor.getJavadocPolicy());

      PsiField field = fieldDescriptor.getField();
      final PsiDocComment docComment = field.getDocComment();
      if (myDescriptor.isToEncapsulateGet()) {
        final PsiMethod prototype = fieldDescriptor.getGetterPrototype();
        assert prototype != null;
        final PsiMethod getter = addOrChangeAccessor(prototype, myNameToGetter);
        if (docComment != null) {
          final PsiDocComment getterJavadoc =
              (PsiDocComment) getter.addBefore(docComment, getter.getFirstChild());
          commentPolicy.processNewJavaDoc(getterJavadoc);
        }
      }
      if (myDescriptor.isToEncapsulateSet() && !field.hasModifierProperty(PsiModifier.FINAL)) {
        PsiMethod prototype = fieldDescriptor.getSetterPrototype();
        assert prototype != null;
        addOrChangeAccessor(prototype, myNameToSetter);
      }

      if (docComment != null) {
        commentPolicy.processOldJavaDoc(docComment);
      }
    }
  }
    @Override
    public int compare(PsiVariable o1, PsiVariable o2) {

      if (o1 instanceof PsiParameter && ((PsiParameter) o1).isVarArgs()) return 1;
      if (o2 instanceof PsiParameter && ((PsiParameter) o2).isVarArgs()) return -1;

      if (o1 instanceof PsiField && o2 instanceof PsiField) {
        return o1.getTextOffset() - o2.getTextOffset();
      }
      if (o1 instanceof PsiParameter && o2 instanceof PsiParameter) {
        return myParameterList.getParameterIndex((PsiParameter) o1)
            - myParameterList.getParameterIndex((PsiParameter) o2);
      }

      if (o1 instanceof PsiField && o2 instanceof PsiParameter) {
        final PsiField field =
            FieldFromParameterUtils.getParameterAssignedToField((PsiParameter) o2);
        if (field == null) return 1;
        return o1.getTextOffset() - field.getTextOffset();
      }
      if (o1 instanceof PsiParameter && o2 instanceof PsiField) {
        final PsiField field =
            FieldFromParameterUtils.getParameterAssignedToField((PsiParameter) o1);
        if (field == null) return -1;
        return field.getTextOffset() - o2.getTextOffset();
      }

      return 0;
    }
  private static boolean processField(
      @NotNull GrTypeDefinition grType,
      @NotNull PsiScopeProcessor processor,
      @NotNull ResolveState state,
      @NotNull PsiElement place,
      boolean processInstanceMethods,
      @NotNull PsiSubstitutor substitutor,
      @NotNull PsiElementFactory factory,
      @NotNull LanguageLevel level,
      CandidateInfo fieldInfo) {
    final PsiField field = (PsiField) fieldInfo.getElement();
    if (!processInstanceMember(processInstanceMethods, field) || isSameDeclaration(place, field)) {
      return true;
    }
    LOG.assertTrue(field.getContainingClass() != null);
    final PsiSubstitutor finalSubstitutor =
        PsiClassImplUtil.obtainFinalSubstitutor(
            field.getContainingClass(),
            fieldInfo.getSubstitutor(),
            grType,
            substitutor,
            factory,
            level);

    return processor.execute(field, state.put(PsiSubstitutor.KEY, finalSubstitutor));
  }
 private static boolean doCreate(
     Project project,
     Editor editor,
     PsiParameter[] parameters,
     SmartPsiElementPointer constructorPointer,
     ParameterInfoImpl[] parameterInfos,
     HashMap<PsiField, String> fields) {
   PsiMethod constructor = (PsiMethod) constructorPointer.getElement();
   assert constructor != null;
   PsiParameter[] newParameters = constructor.getParameterList().getParameters();
   if (newParameters == parameters) return false; // user must have canceled dialog
   boolean created = false;
   // do not introduce assignment in chanined constructor
   if (JavaHighlightUtil.getChainedConstructors(constructor) == null) {
     for (PsiField field : fields.keySet()) {
       final String defaultParamName = fields.get(field);
       PsiParameter parameter =
           findParamByName(defaultParamName, field.getType(), newParameters, parameterInfos);
       if (parameter == null) {
         continue;
       }
       notNull(project, field, parameter);
       AssignFieldFromParameterAction.addFieldAssignmentStatement(
           project, field, parameter, editor);
       created = true;
     }
   }
   return created;
 }
 public CreateConstructorParameterFromFieldFix(@NotNull PsiField field) {
   myClass = field.getContainingClass();
   myField =
       SmartPointerManager.getInstance(field.getProject()).createSmartPsiElementPointer(field);
   if (myClass != null) {
     getFieldsToFix().add(myField);
   }
 }
  public Collection<PsiElement> getAdditionalElementsToDelete(
      @NotNull final PsiElement element,
      @NotNull final Collection<PsiElement> allElementsToDelete,
      final boolean askUser) {
    if (element instanceof PsiField) {
      PsiField field = (PsiField) element;
      final Project project = element.getProject();
      String propertyName =
          JavaCodeStyleManager.getInstance(project)
              .variableNameToPropertyName(field.getName(), VariableKind.FIELD);

      PsiClass aClass = field.getContainingClass();
      if (aClass != null) {
        boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
        PsiMethod[] getters =
            GetterSetterPrototypeProvider.findGetters(aClass, propertyName, isStatic);
        if (getters != null) {
          final List<PsiMethod> validGetters = new ArrayList<>(1);
          for (PsiMethod getter : getters) {
            if (!allElementsToDelete.contains(getter) && (getter != null && getter.isPhysical())) {
              validGetters.add(getter);
            }
          }
          getters =
              validGetters.isEmpty()
                  ? null
                  : validGetters.toArray(new PsiMethod[validGetters.size()]);
        }

        PsiMethod setter = PropertyUtil.findPropertySetter(aClass, propertyName, isStatic, false);
        if (allElementsToDelete.contains(setter) || setter != null && !setter.isPhysical())
          setter = null;
        if (askUser && (getters != null || setter != null)) {
          final String message =
              RefactoringMessageUtil.getGetterSetterMessage(
                  field.getName(),
                  RefactoringBundle.message("delete.title"),
                  getters != null ? getters[0] : null,
                  setter);
          if (!ApplicationManager.getApplication().isUnitTestMode()
              && Messages.showYesNoDialog(
                      project,
                      message,
                      RefactoringBundle.message("safe.delete.title"),
                      Messages.getQuestionIcon())
                  != Messages.YES) {
            getters = null;
            setter = null;
          }
        }
        List<PsiElement> elements = new ArrayList<>();
        if (setter != null) elements.add(setter);
        if (getters != null) Collections.addAll(elements, getters);
        return elements;
      }
    }
    return null;
  }
 private boolean existsFieldWithName(String name) {
   final PsiField[] allFields = sourceClass.getAllFields();
   for (PsiField field : allFields) {
     if (name.equals(field.getName()) && !fields.contains(field)) {
       return true;
     }
   }
   return false;
 }
 private static boolean isAvailable(PsiField field) {
   PsiClass containingClass = field == null ? null : field.getContainingClass();
   return field != null
       && field.getManager().isInProject(field)
       && !field.hasModifierProperty(PsiModifier.STATIC)
       && containingClass != null
       && !(containingClass instanceof PsiSyntheticClass)
       && containingClass.getName() != null;
 }
 public ExtractClassProcessor(
     PsiClass sourceClass,
     List<PsiField> fields,
     List<PsiMethod> methods,
     List<PsiClass> classes,
     String packageName,
     MoveDestination moveDestination,
     String newClassName,
     String newVisibility,
     boolean generateAccessors,
     List<MemberInfo> enumConstants) {
   super(sourceClass.getProject());
   this.sourceClass = sourceClass;
   this.newPackageName = packageName;
   myMoveDestination = moveDestination;
   myNewVisibility = newVisibility;
   myGenerateAccessors = generateAccessors;
   this.enumConstants = new ArrayList<PsiField>();
   for (MemberInfo constant : enumConstants) {
     if (constant.isChecked()) {
       this.enumConstants.add((PsiField) constant.getMember());
     }
   }
   this.fields = new ArrayList<PsiField>(fields);
   this.methods = new ArrayList<PsiMethod>(methods);
   this.innerClasses = new ArrayList<PsiClass>(classes);
   this.newClassName = newClassName;
   delegateFieldName = calculateDelegateFieldName();
   requiresBackpointer =
       new BackpointerUsageVisitor(fields, innerClasses, methods, sourceClass)
           .backpointerRequired();
   if (requiresBackpointer) {
     ContainerUtil.addAll(typeParams, sourceClass.getTypeParameters());
   } else {
     final Set<PsiTypeParameter> typeParamSet = new HashSet<PsiTypeParameter>();
     final TypeParametersVisitor visitor = new TypeParametersVisitor(typeParamSet);
     for (PsiField field : fields) {
       field.accept(visitor);
     }
     for (PsiMethod method : methods) {
       method.accept(visitor);
       // do not include method's type parameters in class signature
       typeParamSet.removeAll(Arrays.asList(method.getTypeParameters()));
     }
     typeParams.addAll(typeParamSet);
   }
   myClass =
       new WriteCommandAction<PsiClass>(myProject, getCommandName()) {
         @Override
         protected void run(@NotNull Result<PsiClass> result) throws Throwable {
           result.setResult(buildClass());
         }
       }.execute().getResultObject();
   myExtractEnumProcessor = new ExtractEnumProcessor(myProject, this.enumConstants, myClass);
 }
예제 #14
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;
    }
  }
 public void visitReferenceExpression(PsiReferenceExpression expression) {
   super.visitReferenceExpression(expression);
   if (isProhibitedReference(expression)) {
     final PsiField field = getReferencedField(expression);
     if (!hasGetter(field)
         && !isStaticFinal(field)
         && !field.getModifierList().hasModifierProperty(PsiModifier.PUBLIC)) {
       fieldsNeedingGetter.add(field);
     }
   }
 }
 private static boolean isCompileTimeFlagReference(PsiElement element) {
   PsiElement resolved =
       element instanceof PsiReferenceExpression
           ? ((PsiReferenceExpression) element).resolve()
           : null;
   if (!(resolved instanceof PsiField)) return false;
   PsiField field = (PsiField) resolved;
   return field.hasModifierProperty(PsiModifier.FINAL)
       && field.hasModifierProperty(PsiModifier.STATIC)
       && PsiType.BOOLEAN.equals(field.getType());
 }
예제 #17
0
  @Nullable
  public static PsiField findPropertyField(
      Project project, PsiClass aClass, String propertyName, boolean isStatic) {
    PsiField[] fields = aClass.getAllFields();

    for (PsiField field : fields) {
      if (field.hasModifierProperty(PsiModifier.STATIC) != isStatic) continue;
      if (propertyName.equals(suggestPropertyName(project, field))) return field;
    }

    return null;
  }
    public void visitAssignmentExpression(PsiAssignmentExpression expression) {
      super.visitAssignmentExpression(expression);

      final PsiExpression lhs = expression.getLExpression();
      if (isProhibitedReference(lhs)) {
        final PsiField field = getReferencedField(lhs);
        if (!hasGetter(field)
            && !isStaticFinal(field)
            && !field.getModifierList().hasModifierProperty(PsiModifier.PUBLIC)) {
          fieldsNeedingSetter.add(field);
        }
      }
    }
  @Override
  protected boolean preprocessUsages(@NotNull final Ref<UsageInfo[]> refUsages) {
    final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
    myExtractEnumProcessor.findEnumConstantConflicts(refUsages);
    if (!DestinationFolderComboBox.isAccessible(
        myProject,
        sourceClass.getContainingFile().getVirtualFile(),
        myClass.getContainingFile().getContainingDirectory().getVirtualFile())) {
      conflicts.putValue(
          sourceClass,
          "Extracted class won't be accessible in "
              + RefactoringUIUtil.getDescription(sourceClass, true));
    }
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                myClass.delete();
              }
            });
    final Project project = sourceClass.getProject();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    final PsiClass existingClass =
        JavaPsiFacade.getInstance(project).findClass(getQualifiedName(), scope);
    if (existingClass != null) {
      conflicts.putValue(
          existingClass,
          RefactorJBundle.message("cannot.perform.the.refactoring")
              + RefactorJBundle.message("there.already.exists.a.class.with.the.chosen.name"));
    }

    if (!myGenerateAccessors) {
      calculateInitializersConflicts(conflicts);
      final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass();
      final NecessaryAccessorsVisitor srcVisitor = checkNecessaryGettersSetters4SourceClass();
      final Set<PsiField> fieldsNeedingGetter = new LinkedHashSet<PsiField>();
      fieldsNeedingGetter.addAll(visitor.getFieldsNeedingGetter());
      fieldsNeedingGetter.addAll(srcVisitor.getFieldsNeedingGetter());
      for (PsiField field : fieldsNeedingGetter) {
        conflicts.putValue(field, "Field \'" + field.getName() + "\' needs getter");
      }
      final Set<PsiField> fieldsNeedingSetter = new LinkedHashSet<PsiField>();
      fieldsNeedingSetter.addAll(visitor.getFieldsNeedingSetter());
      fieldsNeedingSetter.addAll(srcVisitor.getFieldsNeedingSetter());
      for (PsiField field : fieldsNeedingSetter) {
        conflicts.putValue(field, "Field \'" + field.getName() + "\' needs setter");
      }
    }
    checkConflicts(refUsages, conflicts);
    return showConflicts(conflicts, refUsages.get());
  }
  public static boolean isFieldEquivalentTo(@NotNull PsiField field, PsiElement another) {
    if (!(another instanceof PsiField)) return false;
    String name1 = field.getName();
    if (name1 == null) return false;
    if (!another.isValid()) return false;

    String name2 = ((PsiField) another).getName();
    if (!name1.equals(name2)) return false;
    PsiClass aClass1 = field.getContainingClass();
    PsiClass aClass2 = ((PsiField) another).getContainingClass();
    return aClass1 != null
        && aClass2 != null
        && field.getManager().areElementsEquivalent(aClass1, aClass2);
  }
 @Nullable
 private static PsiField getReferencedFinalField(final PsiExpression argument) {
   if (argument instanceof PsiReferenceExpression) {
     final PsiElement element = ((PsiReferenceExpression) argument).resolve();
     if (element instanceof PsiField) {
       final PsiField field = (PsiField) element;
       final PsiModifierList modifierList = field.getModifierList();
       if (modifierList != null && modifierList.hasModifierProperty(PsiModifier.FINAL)) {
         return field;
       }
     }
   }
   return null;
 }
  @Nullable
  public static PsiField findFieldByName(
      GrTypeDefinition grType, String name, boolean checkBases, boolean includeSynthetic) {
    if (!checkBases) {
      for (PsiField field : CollectClassMembersUtil.getFields(grType, includeSynthetic)) {
        if (name.equals(field.getName())) return field;
      }

      return null;
    }

    Map<String, CandidateInfo> fieldsMap =
        CollectClassMembersUtil.getAllFields(grType, includeSynthetic);
    final CandidateInfo info = fieldsMap.get(name);
    return info == null ? null : (PsiField) info.getElement();
  }
 private static void addFieldsUsages(
     final PsiClass aClass,
     final Processor<UsageInfo> results,
     final JavaClassFindUsagesOptions options) {
   if (options.isIncludeInherited) {
     final PsiManager manager = aClass.getManager();
     PsiField[] fields = aClass.getAllFields();
     FieldsLoop:
     for (int i = 0; i < fields.length; i++) {
       final PsiField field = fields[i];
       // filter hidden fields
       for (int j = 0; j < i; j++) {
         if (Comparing.strEqual(field.getName(), fields[j].getName())) continue FieldsLoop;
       }
       final PsiClass fieldClass = field.getContainingClass();
       if (manager.areElementsEquivalent(fieldClass, aClass)) {
         addElementUsages(fields[i], results, options);
       } else {
         ReferencesSearch.search(
                 new ReferencesSearch.SearchParameters(
                     field, options.searchScope, false, options.fastTrack))
             .forEach(
                 new ReadActionProcessor<PsiReference>() {
                   @Override
                   public boolean processInReadAction(final PsiReference reference) {
                     addResultFromReference(
                         reference, fieldClass, manager, aClass, results, options);
                     return true;
                   }
                 });
       }
     }
   } else {
     PsiField[] fields =
         ApplicationManager.getApplication()
             .runReadAction(
                 new Computable<PsiField[]>() {
                   @Override
                   public PsiField[] compute() {
                     return aClass.getFields();
                   }
                 });
     for (PsiField field : fields) {
       addElementUsages(field, results, options);
     }
   }
 }
예제 #24
0
  @Nullable
  public static PsiField findPropertyFieldWithType(
      Project project,
      String propertyName,
      boolean isStatic,
      PsiType type,
      Iterator<PsiField> fields) {
    while (fields.hasNext()) {
      PsiField field = fields.next();
      if (field.hasModifierProperty(PsiModifier.STATIC) != isStatic) continue;
      if (propertyName.equals(suggestPropertyName(project, field))) {
        if (type.equals(field.getType())) return field;
      }
    }

    return null;
  }
예제 #25
0
  @NotNull
  private Set<String> addAllRestrictedProperties() {
    if (myRefExpr.getQualifier() != null) {
      return Collections.emptySet();
    }

    Set<String> propertyNames = new HashSet<String>();
    for (GrTypeDefinition containingClass =
            PsiTreeUtil.getParentOfType(myRefExpr, GrTypeDefinition.class);
        containingClass != null;
        containingClass = PsiTreeUtil.getParentOfType(containingClass, GrTypeDefinition.class)) {
      for (PsiField field : containingClass.getFields()) {
        propertyNames.add(field.getName());
      }
    }
    return propertyNames;
  }
  private static boolean isCompileConstantInIfCondition(PsiElement element) {
    if (!(element instanceof PsiReferenceExpression)) return false;
    PsiElement resolved = ((PsiReferenceExpression) element).resolve();
    if (!(resolved instanceof PsiField)) return false;
    PsiField field = (PsiField) resolved;

    if (!field.hasModifierProperty(PsiModifier.FINAL)) return false;
    if (!field.hasModifierProperty(PsiModifier.STATIC)) return false;

    PsiElement parent = element.getParent();
    if (parent instanceof PsiPrefixExpression
        && ((PsiPrefixExpression) parent).getOperationTokenType() == JavaTokenType.EXCL) {
      element = parent;
      parent = parent.getParent();
    }
    return parent instanceof PsiIfStatement && ((PsiIfStatement) parent).getCondition() == element;
  }
 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);
   }
 }
  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()]);
  }
 public static void setNewFieldVisibility(PsiField field, EncapsulateFieldsDescriptor descriptor) {
   try {
     if (descriptor.getFieldsVisibility() != null) {
       field.normalizeDeclaration();
       PsiUtil.setModifierProperty(field, descriptor.getFieldsVisibility(), true);
     }
   } catch (IncorrectOperationException e) {
     LOG.error(e);
   }
 }
  public void updateReturnValueTemplate(PsiExpression expression) {
    if (myReturnValueTemplate == null) return;

    if (!getSuperMethods().isEmpty()) {
      for (final RefMethod refMethod : getSuperMethods()) {
        RefMethodImpl refSuper = (RefMethodImpl) refMethod;
        refSuper.updateReturnValueTemplate(expression);
      }
    } else {
      String newTemplate = null;
      final RefJavaUtil refUtil = RefJavaUtil.getInstance();
      if (expression instanceof PsiLiteralExpression) {
        PsiLiteralExpression psiLiteralExpression = (PsiLiteralExpression) expression;
        newTemplate = psiLiteralExpression.getText();
      } else if (expression instanceof PsiReferenceExpression) {
        PsiReferenceExpression referenceExpression = (PsiReferenceExpression) expression;
        PsiElement resolved = referenceExpression.resolve();
        if (resolved instanceof PsiField) {
          PsiField psiField = (PsiField) resolved;
          if (psiField.hasModifierProperty(PsiModifier.STATIC)
              && psiField.hasModifierProperty(PsiModifier.FINAL)
              && refUtil.compareAccess(refUtil.getAccessModifier(psiField), getAccessModifier())
                  >= 0) {
            newTemplate =
                PsiFormatUtil.formatVariable(
                    psiField,
                    PsiFormatUtilBase.SHOW_NAME
                        | PsiFormatUtilBase.SHOW_CONTAINING_CLASS
                        | PsiFormatUtilBase.SHOW_FQ_NAME,
                    PsiSubstitutor.EMPTY);
          }
        }
      } else if (refUtil.isCallToSuperMethod(expression, (PsiMethod) getElement())) return;

      //noinspection StringEquality
      if (myReturnValueTemplate == RETURN_VALUE_UNDEFINED) {
        myReturnValueTemplate = newTemplate;
      } else if (!Comparing.equal(myReturnValueTemplate, newTemplate)) {
        myReturnValueTemplate = null;
      }
    }
  }