Exemplo n.º 1
0
    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      final PsiElement element = descriptor.getPsiElement();
      final PsiModifierListOwner psiElement =
          PsiTreeUtil.getParentOfType(element, PsiModifierListOwner.class);
      if (psiElement != null) {
        RefJavaElement refElement =
            (RefJavaElement) (myManager != null ? myManager.getReference(psiElement) : null);
        try {
          if (psiElement instanceof PsiVariable) {
            ((PsiVariable) psiElement).normalizeDeclaration();
          }
          final PsiModifierList modifierList = psiElement.getModifierList();
          LOG.assertTrue(modifierList != null);
          modifierList.setModifierProperty(PsiModifier.FINAL, true);
          modifierList.setModifierProperty(PsiModifier.VOLATILE, false);
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }

        if (refElement != null) {
          RefJavaUtil.getInstance().setIsFinal(refElement, true);
        }
      }
    }
  @Override
  protected void invokeImpl(final PsiClass targetClass) {
    PsiNewExpression newExpression = getNewExpression();
    PsiJavaCodeReferenceElement ref = newExpression.getClassOrAnonymousClassReference();
    assert ref != null;
    String refName = ref.getReferenceName();
    LOG.assertTrue(refName != null);
    PsiElementFactory elementFactory =
        JavaPsiFacade.getInstance(newExpression.getProject()).getElementFactory();
    PsiClass created = elementFactory.createClass(refName);
    final PsiModifierList modifierList = created.getModifierList();
    LOG.assertTrue(modifierList != null);
    if (PsiTreeUtil.isAncestor(targetClass, newExpression, true)) {
      if (targetClass.isInterface()) {
        modifierList.setModifierProperty(PsiModifier.PACKAGE_LOCAL, true);
      } else {
        modifierList.setModifierProperty(PsiModifier.PRIVATE, true);
      }
    }

    if (!PsiTreeUtil.isAncestor(targetClass, newExpression, true)
        || PsiUtil.getEnclosingStaticElement(newExpression, targetClass) != null
        || isInThisOrSuperCall(newExpression)) {
      modifierList.setModifierProperty(PsiModifier.STATIC, true);
    }
    created = (PsiClass) targetClass.add(created);

    setupClassFromNewExpression(created, newExpression);

    setupGenericParameters(created, ref);
  }
 private void makeStatic(PsiMethod member) {
   final PsiAnnotation overrideAnnotation =
       AnnotationUtil.findAnnotation(member, CommonClassNames.JAVA_LANG_OVERRIDE);
   if (overrideAnnotation != null) {
     overrideAnnotation.delete();
   }
   setupTypeParameterList(member);
   // Add static modifier
   final PsiModifierList modifierList = member.getModifierList();
   modifierList.setModifierProperty(PsiModifier.STATIC, true);
   modifierList.setModifierProperty(PsiModifier.FINAL, false);
   modifierList.setModifierProperty(PsiModifier.DEFAULT, false);
 }
 private static void makeMemberPackageLocal(PsiElement element) {
   final PsiElement parent = element.getParent();
   final PsiReferenceExpression reference = (PsiReferenceExpression) parent;
   final PsiModifierListOwner member = (PsiModifierListOwner) reference.resolve();
   if (member == null) {
     return;
   }
   final PsiModifierList modifiers = member.getModifierList();
   if (modifiers == null) {
     return;
   }
   modifiers.setModifierProperty(PsiModifier.PUBLIC, false);
   modifiers.setModifierProperty(PsiModifier.PROTECTED, false);
   modifiers.setModifierProperty(PsiModifier.PRIVATE, false);
 }
  private static void makeVariableFinalIfNeeded(
      InsertionContext context, @Nullable PsiReferenceExpression ref) {
    if (!Registry.is("java.completion.make.outer.variables.final")
        || ref == null
        || PsiUtil.isLanguageLevel8OrHigher(ref)
        || JspPsiUtil.isInJspFile(ref)) {
      return;
    }

    PsiElement target = ref.resolve();
    if (target instanceof PsiLocalVariable || target instanceof PsiParameter) {
      PsiClass placeClass =
          PsiTreeUtil.findElementOfClassAtOffset(
              context.getFile(), context.getTailOffset() - 1, PsiClass.class, false);
      if (placeClass != null
          && !PsiTreeUtil.isAncestor(placeClass, target, true)
          && !HighlightControlFlowUtil.isReassigned(
              (PsiVariable) target,
              new HashMap<PsiElement, Collection<ControlFlowUtil.VariableInfo>>())) {
        PsiModifierList modifierList = ((PsiVariable) target).getModifierList();
        if (modifierList != null) {
          modifierList.setModifierProperty(PsiModifier.FINAL, true);
        }
      }
    }
  }
 public void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiElement element = descriptor.getPsiElement();
   final PsiModifierList modifierList;
   if (element instanceof PsiModifierList) {
     modifierList = (PsiModifierList) element;
   } else {
     modifierList = (PsiModifierList) element.getParent();
   }
   assert modifierList != null;
   if (modifierList.getParent() instanceof PsiClass) {
     modifierList.setModifierProperty(PsiModifier.STATIC, false);
   } else {
     modifierList.setModifierProperty(PsiModifier.PRIVATE, false);
   }
 }
  private static boolean canBePrivate(
      PsiMethod method,
      Collection<PsiReference> references,
      Collection<? extends PsiElement> deleted,
      final PsiElement[] allElementsToDelete) {
    final PsiClass containingClass = method.getContainingClass();
    if (containingClass == null) {
      return false;
    }

    PsiManager manager = method.getManager();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    final PsiElementFactory factory = facade.getElementFactory();
    final PsiModifierList privateModifierList;
    try {
      final PsiMethod newMethod = factory.createMethod("x3", PsiType.VOID);
      privateModifierList = newMethod.getModifierList();
      privateModifierList.setModifierProperty(PsiModifier.PRIVATE, true);
    } catch (IncorrectOperationException e) {
      LOG.assertTrue(false);
      return false;
    }
    for (PsiReference reference : references) {
      final PsiElement element = reference.getElement();
      if (!isInside(element, allElementsToDelete)
          && !isInside(element, deleted)
          && !facade
              .getResolveHelper()
              .isAccessible(method, privateModifierList, element, null, null)) {
        return false;
      }
    }
    return true;
  }
Exemplo n.º 8
0
 private void changeModifierList(PsiModifierList modifierList) {
   try {
     modifierList.setModifierProperty(myModifier, myShouldHave);
   } catch (IncorrectOperationException e) {
     LOG.error(e);
   }
 }
 @Override
 public void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiElement classNameIdentifier = descriptor.getPsiElement();
   final PsiClass aClass = (PsiClass) classNameIdentifier.getParent();
   if (aClass == null) {
     return;
   }
   final PsiMethod[] constructurs = aClass.getConstructors();
   for (final PsiMethod constructor : constructurs) {
     final PsiParameterList parameterList = constructor.getParameterList();
     if (parameterList.getParametersCount() == 0) {
       final PsiModifierList modifiers = constructor.getModifierList();
       modifiers.setModifierProperty(PsiModifier.PUBLIC, false);
       modifiers.setModifierProperty(PsiModifier.PROTECTED, false);
       modifiers.setModifierProperty(PsiModifier.PRIVATE, true);
     }
   }
 }
    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!FileModificationService.getInstance()
          .preparePsiElementForWrite(descriptor.getPsiElement())) return;
      final PsiModifierListOwner element =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiModifierListOwner.class);
      if (element != null) {
        RefElement refElement = null;
        if (myManager != null) {
          refElement = myManager.getReference(element);
        }
        try {
          if (element instanceof PsiVariable) {
            ((PsiVariable) element).normalizeDeclaration();
          }

          PsiModifierList list = element.getModifierList();

          LOG.assertTrue(list != null);

          if (element instanceof PsiMethod) {
            PsiMethod psiMethod = (PsiMethod) element;
            PsiClass containingClass = psiMethod.getContainingClass();
            if (containingClass != null
                && containingClass.getParent() instanceof PsiFile
                && myHint == PsiModifier.PRIVATE
                && list.hasModifierProperty(PsiModifier.FINAL)) {
              list.setModifierProperty(PsiModifier.FINAL, false);
            }
          }

          list.setModifierProperty(myHint, true);
          if (refElement instanceof RefJavaElement) {
            RefJavaUtil.getInstance().setAccessModifier((RefJavaElement) refElement, myHint);
          }
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }
    }
 private static void makeConstructorPackageLocal(Project project, PsiElement element) {
   final PsiNewExpression newExpression =
       PsiTreeUtil.getParentOfType(element, PsiNewExpression.class);
   if (newExpression == null) {
     return;
   }
   final PsiMethod constructor = newExpression.resolveConstructor();
   if (constructor != null) {
     final PsiModifierList modifierList = constructor.getModifierList();
     modifierList.setModifierProperty(PsiModifier.PRIVATE, false);
     return;
   }
   final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement) element;
   final PsiElement target = referenceElement.resolve();
   if (!(target instanceof PsiClass)) {
     return;
   }
   final PsiClass aClass = (PsiClass) target;
   final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
   final PsiMethod newConstructor = elementFactory.createConstructor();
   final PsiModifierList modifierList = newConstructor.getModifierList();
   modifierList.setModifierProperty(PsiModifier.PACKAGE_LOCAL, true);
   aClass.add(newConstructor);
 }
 private static PsiDeclarationStatement createNewDeclaration(
     @NotNull PsiLocalVariable variable, PsiExpression initializer)
     throws IncorrectOperationException {
   final PsiManager manager = variable.getManager();
   final PsiElementFactory factory =
       JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
   final PsiDeclarationStatement newDeclaration =
       factory.createVariableDeclarationStatement(
           variable.getName(), variable.getType(), initializer);
   if (variable.hasModifierProperty(PsiModifier.FINAL)) {
     final PsiLocalVariable newVariable =
         (PsiLocalVariable) newDeclaration.getDeclaredElements()[0];
     final PsiModifierList modifierList = newVariable.getModifierList();
     modifierList.setModifierProperty(PsiModifier.FINAL, true);
   }
   return newDeclaration;
 }
 @Override
 public void doFix(Project project, ProblemDescriptor descriptor)
     throws IncorrectOperationException {
   final PsiElement classNameIdentifier = descriptor.getPsiElement();
   final PsiClass aClass = (PsiClass) classNameIdentifier.getParent();
   if (aClass == null) {
     return;
   }
   final PsiManager psiManager = PsiManager.getInstance(project);
   final PsiElementFactory factory =
       JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
   final PsiMethod constructor = factory.createConstructor();
   final PsiModifierList modifierList = constructor.getModifierList();
   modifierList.setModifierProperty(PsiModifier.PRIVATE, true);
   aClass.add(constructor);
   final CodeStyleManager styleManager = psiManager.getCodeStyleManager();
   styleManager.reformat(constructor);
 }
  private PsiClass buildClass() {
    final PsiManager manager = sourceClass.getManager();
    final Project project = sourceClass.getProject();
    final ExtractedClassBuilder extractedClassBuilder = new ExtractedClassBuilder();
    extractedClassBuilder.setProject(myProject);
    extractedClassBuilder.setClassName(newClassName);
    extractedClassBuilder.setPackageName(newPackageName);
    extractedClassBuilder.setOriginalClassName(sourceClass.getQualifiedName());
    extractedClassBuilder.setRequiresBackPointer(requiresBackpointer);
    extractedClassBuilder.setExtractAsEnum(enumConstants);
    for (PsiField field : fields) {
      extractedClassBuilder.addField(field);
    }
    for (PsiMethod method : methods) {
      extractedClassBuilder.addMethod(method);
    }
    for (PsiClass innerClass : innerClasses) {
      extractedClassBuilder.addInnerClass(
          innerClass, innerClassesToMakePublic.contains(innerClass));
    }
    extractedClassBuilder.setTypeArguments(typeParams);
    final List<PsiClass> interfaces = calculateInterfacesSupported();
    extractedClassBuilder.setInterfaces(interfaces);

    if (myGenerateAccessors) {
      final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass();
      sourceClass.accept(visitor);
      extractedClassBuilder.setFieldsNeedingGetters(visitor.getFieldsNeedingGetter());
      extractedClassBuilder.setFieldsNeedingSetters(visitor.getFieldsNeedingSetter());
    }

    final String classString = extractedClassBuilder.buildBeanClass();
    if (extractInnerClass) {
      final PsiFileFactory factory = PsiFileFactory.getInstance(project);
      final PsiJavaFile newFile =
          (PsiJavaFile)
              factory.createFileFromText(
                  newClassName + ".java", JavaFileType.INSTANCE, classString);
      final PsiClass psiClass = newFile.getClasses()[0];
      if (!psiClass.isEnum()) {
        final PsiModifierList modifierList = psiClass.getModifierList();
        assert modifierList != null;
        modifierList.setModifierProperty(PsiModifier.STATIC, true);
      }
      final PsiElement addedClass = sourceClass.add(psiClass);
      return (PsiClass)
          CodeStyleManager.getInstance(manager)
              .reformat(
                  JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedClass));
    }

    try {
      final PsiFile containingFile = sourceClass.getContainingFile();
      final PsiDirectory directory;
      final PsiDirectory containingDirectory = containingFile.getContainingDirectory();
      if (myMoveDestination != null) {
        directory = myMoveDestination.getTargetDirectory(containingDirectory);
      } else {
        final Module module = ModuleUtil.findModuleForPsiElement(containingFile);
        assert module != null;
        directory =
            PackageUtil.findOrCreateDirectoryForPackage(
                module, newPackageName, containingDirectory, false, true);
      }
      if (directory != null) {
        final PsiFileFactory factory = PsiFileFactory.getInstance(project);
        final PsiFile newFile =
            factory.createFileFromText(newClassName + ".java", JavaFileType.INSTANCE, classString);
        final PsiElement addedFile = directory.add(newFile);
        final CodeStyleManager codeStyleManager =
            CodeStyleManager.getInstance(manager.getProject());
        final PsiElement shortenedFile =
            JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedFile);
        return ((PsiJavaFile) codeStyleManager.reformat(shortenedFile)).getClasses()[0];
      } else {
        return null;
      }
    } catch (IncorrectOperationException e) {
      return null;
    }
  }
  public static void createFieldAndAddAssignment(
      final @NotNull Project project,
      final @NotNull PsiClass targetClass,
      final @NotNull PsiMethod method,
      final @NotNull PsiParameter parameter,
      final @NotNull PsiType fieldType,
      final @NotNull String fieldName,
      final boolean isStatic,
      final boolean isFinal)
      throws IncorrectOperationException {
    PsiManager psiManager = PsiManager.getInstance(project);
    PsiElementFactory factory =
        JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();

    PsiField field = factory.createField(fieldName, fieldType);
    PsiModifierList modifierList = field.getModifierList();

    if (modifierList == null) return;
    modifierList.setModifierProperty(PsiModifier.STATIC, isStatic);
    modifierList.setModifierProperty(PsiModifier.FINAL, isFinal);

    NullableNotNullManager.getInstance(project).copyNullableOrNotNullAnnotation(parameter, field);

    PsiCodeBlock methodBody = method.getBody();
    if (methodBody == null) return;
    PsiStatement[] statements = methodBody.getStatements();

    Ref<Pair<PsiField, Boolean>> anchorRef = new Ref<Pair<PsiField, Boolean>>();
    int i = findFieldAssignmentAnchor(statements, anchorRef, targetClass, parameter);
    Pair<PsiField, Boolean> fieldAnchor = anchorRef.get();

    String stmtText = fieldName + " = " + parameter.getName() + ";";
    if (fieldName.equals(parameter.getName())) {
      @NonNls
      String prefix =
          isStatic ? targetClass.getName() == null ? "" : targetClass.getName() + "." : "this.";
      stmtText = prefix + stmtText;
    }

    PsiStatement assignmentStmt = factory.createStatementFromText(stmtText, methodBody);
    assignmentStmt = (PsiStatement) CodeStyleManager.getInstance(project).reformat(assignmentStmt);

    if (i == statements.length) {
      methodBody.add(assignmentStmt);
    } else {
      methodBody.addAfter(assignmentStmt, i > 0 ? statements[i - 1] : null);
    }

    if (fieldAnchor != null) {
      PsiVariable psiVariable = fieldAnchor.getFirst();
      psiVariable.normalizeDeclaration();
    }

    if (targetClass.findFieldByName(fieldName, false) == null) {
      if (fieldAnchor != null) {
        Boolean insertBefore = fieldAnchor.getSecond();
        PsiField inField = fieldAnchor.getFirst();
        if (insertBefore.booleanValue()) {
          targetClass.addBefore(field, inField);
        } else {
          targetClass.addAfter(field, inField);
        }
      } else {
        targetClass.add(field);
      }
    }
  }