@Override public void visitMethod(@NotNull PsiMethod method) { // note: no call to super if (method.getNameIdentifier() == null) { return; } if (!method.isConstructor()) { return; } if (ignoreScope != Scope.NONE) { switch (ignoreScope.ordinal()) { case 3: if (method.hasModifierProperty(PsiModifier.PROTECTED)) return; case 2: if (method.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) return; case 1: if (method.hasModifierProperty(PsiModifier.PRIVATE)) return; } } final PsiParameterList parameterList = method.getParameterList(); final int parametersCount = parameterList.getParametersCount(); if (parametersCount <= getLimit()) { return; } registerMethodError(method, Integer.valueOf(parametersCount)); }
@Override public void visitNewExpression(PsiNewExpression expression) { super.visitNewExpression(expression); final PsiJavaCodeReferenceElement classReference = expression.getClassReference(); if (classReference == null) { return; } final String name = classReference.getReferenceName(); if (!"BigDecimal".equals(name)) { return; } final PsiMethod constructor = expression.resolveConstructor(); if (constructor == null) { return; } final PsiParameterList parameterList = constructor.getParameterList(); final int length = parameterList.getParametersCount(); if (length != 1 && length != 2) { return; } final PsiParameter[] parameters = parameterList.getParameters(); final PsiParameter firstParameter = parameters[0]; final PsiType type = firstParameter.getType(); if (type != PsiType.DOUBLE) { return; } registerNewExpressionError(expression); }
@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; }
public IntroduceParameterObjectProcessor( String className, String packageName, MoveDestination moveDestination, PsiMethod method, VariableData[] parameters, boolean keepMethodAsDelegate, final boolean useExistingClass, final boolean createInnerClass, String newVisibility, boolean generateAccessors) { super(method.getProject()); myMoveDestination = moveDestination; this.method = method; this.className = className; this.packageName = packageName; this.keepMethodAsDelegate = keepMethodAsDelegate; myUseExistingClass = useExistingClass; myCreateInnerClass = createInnerClass; myNewVisibility = newVisibility; myGenerateAccessors = generateAccessors; this.parameters = new ArrayList<ParameterChunk>(); for (VariableData parameter : parameters) { this.parameters.add(new ParameterChunk(parameter)); } final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] methodParams = parameterList.getParameters(); paramsToMerge = new int[parameters.length]; for (int p = 0; p < parameters.length; p++) { VariableData parameter = parameters[p]; for (int i = 0; i < methodParams.length; i++) { final PsiParameter methodParam = methodParams[i]; if (parameter.variable.equals(methodParam)) { paramsToMerge[p] = i; break; } } } final Set<PsiTypeParameter> typeParamSet = new HashSet<PsiTypeParameter>(); final PsiTypeVisitor<Object> typeParametersVisitor = new PsiTypeVisitor<Object>() { @Override public Object visitClassType(PsiClassType classType) { final PsiClass referent = classType.resolve(); if (referent instanceof PsiTypeParameter) { typeParamSet.add((PsiTypeParameter) referent); } return super.visitClassType(classType); } }; for (VariableData parameter : parameters) { parameter.type.accept(typeParametersVisitor); } typeParams = new ArrayList<PsiTypeParameter>(typeParamSet); final String qualifiedName = StringUtil.getQualifiedName(packageName, className); final GlobalSearchScope scope = GlobalSearchScope.allScope(myProject); existingClass = JavaPsiFacade.getInstance(myProject).findClass(qualifiedName, scope); }
ParamUsageVisitor(PsiMethod method, int[] paramIndicesToMerge) { super(); final PsiParameterList paramList = method.getParameterList(); final PsiParameter[] parameters = paramList.getParameters(); for (int i : paramIndicesToMerge) { paramsToMerge.add(parameters[i]); } }
private static PsiParameter createNewParameter( JavaChangeInfo changeInfo, JavaParameterInfo newParm, PsiSubstitutor substitutor) throws IncorrectOperationException { final PsiParameterList list = changeInfo.getMethod().getParameterList(); final PsiElementFactory factory = JavaPsiFacade.getInstance(list.getProject()).getElementFactory(); final PsiType type = substitutor.substitute(newParm.createType(list, list.getManager())); return factory.createParameter(newParm.getName(), type); }
static boolean hasNullArgConstructor(PsiClass aClass) { final PsiMethod[] constructors = aClass.getConstructors(); for (final PsiMethod constructor : constructors) { final PsiParameterList params = constructor.getParameterList(); if (params.getParametersCount() == 0) { return true; } } return false; }
@Override public void visitThrowStatement(PsiThrowStatement statement) { super.visitThrowStatement(statement); final PsiCatchSection catchSection = PsiTreeUtil.getParentOfType(statement, PsiCatchSection.class, true, PsiClass.class); if (catchSection == null) { return; } final PsiParameter parameter = catchSection.getParameter(); if (parameter == null) { return; } @NonNls final String parameterName = parameter.getName(); if (PsiUtil.isIgnoredName(parameterName)) { return; } final PsiExpression exception = statement.getException(); if (exception == null) { return; } if (ignoreCantWrap) { final PsiType thrownType = exception.getType(); if (thrownType instanceof PsiClassType) { final PsiClassType classType = (PsiClassType) thrownType; final PsiClass exceptionClass = classType.resolve(); if (exceptionClass != null) { final PsiMethod[] constructors = exceptionClass.getConstructors(); final PsiClassType throwableType = TypeUtils.getType(CommonClassNames.JAVA_LANG_THROWABLE, statement); boolean canWrap = false; outer: for (PsiMethod constructor : constructors) { final PsiParameterList parameterList = constructor.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); for (PsiParameter constructorParameter : parameters) { final PsiType type = constructorParameter.getType(); if (throwableType.equals(type)) { canWrap = true; break outer; } } } if (!canWrap) { return; } } } } final ReferenceFinder visitor = new ReferenceFinder(parameter); exception.accept(visitor); if (visitor.usesParameter()) { return; } registerStatementError(statement); }
@Nullable public static PsiParameter findParameterAtCursor(@NotNull PsiFile file, @NotNull Editor editor) { final int offset = editor.getCaretModel().getOffset(); final PsiParameterList parameterList = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiParameterList.class, false); if (parameterList == null) return null; final PsiParameter[] parameters = parameterList.getParameters(); for (PsiParameter parameter : parameters) { final TextRange range = parameter.getTextRange(); if (range.getStartOffset() <= offset && offset <= range.getEndOffset()) return parameter; } return null; }
private static PsiAnnotation[] getHierarchyAnnotations( PsiModifierListOwner listOwner, PsiModifierList modifierList) { final Set<PsiAnnotation> all = new HashSet<PsiAnnotation>() { public boolean add(PsiAnnotation o) { // don't overwrite "higher level" annotations return !contains(o) && super.add(o); } }; if (listOwner instanceof PsiMethod) { ContainerUtil.addAll(all, modifierList.getAnnotations()); SuperMethodsSearch.search((PsiMethod) listOwner, null, true, true) .forEach( new Processor<MethodSignatureBackedByPsiMethod>() { public boolean process(final MethodSignatureBackedByPsiMethod superMethod) { ContainerUtil.addAll( all, superMethod.getMethod().getModifierList().getAnnotations()); return true; } }); return all.toArray(new PsiAnnotation[all.size()]); } if (listOwner instanceof PsiParameter) { PsiParameter parameter = (PsiParameter) listOwner; PsiElement declarationScope = parameter.getDeclarationScope(); PsiParameterList parameterList; if (declarationScope instanceof PsiMethod && parameter.getParent() == (parameterList = ((PsiMethod) declarationScope).getParameterList())) { PsiMethod method = (PsiMethod) declarationScope; final int parameterIndex = parameterList.getParameterIndex(parameter); ContainerUtil.addAll(all, modifierList.getAnnotations()); SuperMethodsSearch.search(method, null, true, true) .forEach( new Processor<MethodSignatureBackedByPsiMethod>() { public boolean process(final MethodSignatureBackedByPsiMethod superMethod) { PsiParameter superParameter = superMethod.getMethod().getParameterList().getParameters()[parameterIndex]; PsiModifierList modifierList = superParameter.getModifierList(); if (modifierList != null) { ContainerUtil.addAll(all, modifierList.getAnnotations()); } return true; } }); return all.toArray(new PsiAnnotation[all.size()]); } } return modifierList.getAnnotations(); }
@Nullable private static PsiMethod existingClassIsCompatible(PsiClass aClass, List<ParameterChunk> params) { if (params.size() == 1) { final ParameterChunk parameterChunk = params.get(0); final PsiType paramType = parameterChunk.parameter.type; if (TypeConversionUtil.isPrimitiveWrapper(aClass.getQualifiedName())) { parameterChunk.setField(aClass.findFieldByName("value", false)); parameterChunk.setGetter(paramType.getCanonicalText() + "Value"); for (PsiMethod constructor : aClass.getConstructors()) { if (constructorIsCompatible(constructor, params)) return constructor; } } } final PsiMethod[] constructors = aClass.getConstructors(); PsiMethod compatibleConstructor = null; for (PsiMethod constructor : constructors) { if (constructorIsCompatible(constructor, params)) { compatibleConstructor = constructor; break; } } if (compatibleConstructor == null) { return null; } final PsiParameterList parameterList = compatibleConstructor.getParameterList(); final PsiParameter[] constructorParams = parameterList.getParameters(); for (int i = 0; i < constructorParams.length; i++) { final PsiParameter param = constructorParams[i]; final ParameterChunk parameterChunk = params.get(i); final PsiField field = findFieldAssigned(param, compatibleConstructor); if (field == null) { return null; } parameterChunk.setField(field); final PsiMethod getterForField = PropertyUtil.findGetterForField(field); if (getterForField != null) { parameterChunk.setGetter(getterForField.getName()); } final PsiMethod setterForField = PropertyUtil.findSetterForField(field); if (setterForField != null) { parameterChunk.setSetter(setterForField.getName()); } } return compatibleConstructor; }
private static boolean constructorIsCompatible( PsiMethod constructor, List<ParameterChunk> params) { final PsiParameterList parameterList = constructor.getParameterList(); final PsiParameter[] constructorParams = parameterList.getParameters(); if (constructorParams.length != params.size()) { return false; } for (int i = 0; i < constructorParams.length; i++) { if (!TypeConversionUtil.isAssignable( constructorParams[i].getType(), params.get(i).parameter.type)) { return false; } } return true; }
@Nullable private static PsiParameter getAnchorParameter(PsiMethod methodToReplaceIn) { PsiParameterList parameterList = methodToReplaceIn.getParameterList(); final PsiParameter anchorParameter; final PsiParameter[] parameters = parameterList.getParameters(); final int length = parameters.length; if (!methodToReplaceIn.isVarArgs()) { anchorParameter = length > 0 ? parameters[length - 1] : null; } else { LOG.assertTrue(length > 0); LOG.assertTrue(parameters[length - 1].isVarArgs()); anchorParameter = length > 1 ? parameters[length - 2] : null; } return anchorParameter; }
@Override public void visitMethod(@NotNull PsiMethod method) { // note: no call to super; final String methodName = method.getName(); if (!HardcodedMethodConstants.FINALIZE.equals(methodName)) { return; } final PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() != 0) { return; } if (ignoreTrivialFinalizers && isTrivial(method)) { return; } registerMethodError(method); }
private static boolean classHasNoArgConstructor(PsiClass ancestor) { boolean hasConstructor = false; boolean hasNoArgConstructor = false; final PsiMethod[] methods = ancestor.getMethods(); for (final PsiMethod method : methods) { if (method.isConstructor()) { hasConstructor = true; final PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() == 0 && (method.hasModifierProperty(PsiModifier.PUBLIC) || method.hasModifierProperty(PsiModifier.PROTECTED))) { hasNoArgConstructor = true; } } } return hasNoArgConstructor || !hasConstructor; }
public static boolean isDefaultInstantiable(PsiClass psiClass) { final PsiMethod[] constructors = psiClass.getConstructors(); if (constructors.length == 0) { return true; } for (PsiMethod psiMethod : constructors) { final PsiParameterList parameterList = psiMethod.getParameterList(); if (psiMethod.getModifierList().hasModifierProperty("public") && parameterList.getParameters().length == 0) { return true; } } return false; }
@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); } } }
private static boolean usesDefaultClone(PsiClass aClass) { final Project project = aClass.getProject(); final PsiManager manager = aClass.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiClass cloneable = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.lang.Cloneable", scope); if (!InheritanceUtil.isInheritorOrSelf(aClass, cloneable, true)) { return false; } final PsiMethod[] methods = aClass.findMethodsByName("clone", false); for (PsiMethod method : methods) { final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length == 0) { return false; } } return true; }
@Nullable public static PsiParameter getAnchorParameter(PsiParameterList parameterList, boolean isVarArgs) { final PsiParameter[] parameters = parameterList.getParameters(); final int length = parameters.length; if (isVarArgs) { return length > 1 ? parameters[length - 2] : null; } else { return length > 0 ? parameters[length - 1] : null; } }
private boolean hasGoodToString(PsiClass aClass) { final PsiMethod[] methods = aClass.findMethodsByName(HardcodedMethodConstants.TO_STRING, true); for (PsiMethod method : methods) { final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) { continue; } final String name = containingClass.getQualifiedName(); if (CommonClassNames.JAVA_LANG_OBJECT.equals(name)) { continue; } final PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() == 0) { return true; } } return false; }
public JLabel getPopupEntryText(RearrangerSettings settings) { StringBuffer name = new StringBuffer(80); PsiMethod m = (PsiMethod) myEnd; if (m.getReturnTypeElement() != null && !settings.isShowTypeAfterMethod()) { name.append(m.getReturnTypeElement().getText()); name.append(' '); } name.append(m.getName()); PsiParameterList plist = m.getParameterList(); if (settings.isShowParameterNames() || settings.isShowParameterTypes()) { if (plist != null) { name.append("("); for (int i = 0; i < plist.getParameters().length; i++) { if (i > 0) { name.append(", "); } if (settings.isShowParameterTypes()) { String modifiers = plist.getParameters()[i].getModifierList().getText(); if (modifiers.length() > 0) { name.append(modifiers); name.append(' '); } name.append(plist.getParameters()[i].getTypeElement().getText()); if (settings.isShowParameterNames()) { name.append(' '); } } if (settings.isShowParameterNames()) { name.append(plist.getParameters()[i].getName()); } } name.append(")"); } } if (m.getReturnTypeElement() != null && settings.isShowTypeAfterMethod()) { name.append(": "); name.append(m.getReturnTypeElement().getText()); } return new JLabel(name.toString()); }
private boolean hasOnlyMain(PsiClass aClass) { final PsiMethod[] methods = aClass.getMethods(); if (methods.length == 0) { return false; } for (PsiMethod method : methods) { if (method.isConstructor()) { continue; } if (!method.hasModifierProperty(PsiModifier.STATIC)) { return false; } if (method.hasModifierProperty(PsiModifier.PRIVATE)) { continue; } if (!method.hasModifierProperty(PsiModifier.PUBLIC)) { return false; } final String name = method.getName(); if (!name.equals(HardcodedMethodConstants.MAIN)) { return false; } final PsiType returnType = method.getReturnType(); if (!PsiType.VOID.equals(returnType)) { return false; } final PsiParameterList parameterList = method.getParameterList(); if (parameterList.getParametersCount() != 1) { return false; } final PsiParameter[] parameters = parameterList.getParameters(); final PsiParameter parameter = parameters[0]; final PsiType type = parameter.getType(); if (!type.equalsToText("java.lang.String[]")) { return false; } } return true; }
private static boolean isClassHasConstructorWithMap(PsiClass aClass) { PsiMethod[] constructors = aClass.getConstructors(); if (constructors.length == 0) return true; for (PsiMethod constructor : constructors) { PsiParameterList parameterList = constructor.getParameterList(); PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length == 0) return true; final PsiParameter first = parameters[0]; if (InheritanceUtil.isInheritor(first.getType(), CommonClassNames.JAVA_UTIL_MAP)) return true; if (first instanceof GrParameter && ((GrParameter) first).getTypeGroovy() == null) return true; // if constructor has only optional parameters it can be used as default constructor with map // args if (!PsiUtil.isConstructorHasRequiredParameters(constructor)) return true; } return false; }
private static boolean usesDefaultSerialization(PsiClass aClass) { final Project project = aClass.getProject(); final PsiManager manager = aClass.getManager(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final PsiClass serializable = JavaPsiFacade.getInstance(manager.getProject()).findClass("java.io.Serializable", scope); if (!InheritanceUtil.isInheritorOrSelf(aClass, serializable, true)) { return false; } final PsiMethod[] methods = aClass.findMethodsByName("writeObject", false); for (PsiMethod method : methods) { final PsiParameterList parameterList = method.getParameterList(); final PsiParameter[] parameters = parameterList.getParameters(); if (parameters.length == 1) { final PsiType type = parameters[0].getType(); final String text = type.getCanonicalText(); if ("java.io.DataOutputStream".equals(text)) { return false; } } } return true; }
private static void resolveParameterVsFieldsConflicts( final PsiParameter[] newParms, final PsiMethod method, final PsiParameterList list, boolean[] toRemoveParm) throws IncorrectOperationException { List<FieldConflictsResolver> conflictResolvers = new ArrayList<FieldConflictsResolver>(); for (PsiParameter parameter : newParms) { conflictResolvers.add(new FieldConflictsResolver(parameter.getName(), method.getBody())); } ChangeSignatureUtil.synchronizeList( list, Arrays.asList(newParms), ParameterList.INSTANCE, toRemoveParm); JavaCodeStyleManager.getInstance(list.getProject()).shortenClassReferences(list); for (FieldConflictsResolver fieldConflictsResolver : conflictResolvers) { fieldConflictsResolver.fix(); } }
public static int getParameterIndex( @NotNull PsiParameter parameter, @NotNull PsiParameterList parameterList) { PsiParameter[] parameters = parameterList.getParameters(); for (int i = 0; i < parameters.length; i++) { PsiParameter paramInList = parameters[i]; if (parameter.equals(paramInList)) return i; } String name = parameter.getName(); PsiParameter suspect = null; int i; for (i = parameters.length - 1; i >= 0; i--) { PsiParameter paramInList = parameters[i]; if (name.equals(paramInList.getName())) { suspect = paramInList; break; } } String message = parameter + ":" + parameter.getClass() + " not found among parameters: " + Arrays.asList(parameters) + "." + " parameterList' parent: " + parameterList.getParent() + ";" + " parameter.getParent()==paramList: " + (parameter.getParent() == parameterList) + "; " + parameterList.getClass() + ";" + " parameter.isValid()=" + parameter.isValid() + ";" + " parameterList.isValid()= " + parameterList.isValid() + ";" + " parameterList stub: " + (parameterList instanceof StubBasedPsiElement ? ((StubBasedPsiElement) parameterList).getStub() : "---") + "; " + " parameter stub: " + (parameter instanceof StubBasedPsiElement ? ((StubBasedPsiElement) parameter).getStub() : "---") + ";" + " suspect: " + suspect + " (index=" + i + "); " + (suspect == null ? null : suspect.getClass()) + " suspect stub: " + (suspect instanceof StubBasedPsiElement ? ((StubBasedPsiElement) suspect).getStub() : suspect == null ? "-null-" : "---" + suspect.getClass()) + ";" + " parameter.equals(suspect) = " + parameter.equals(suspect) + "; " + " parameter.getNode() == suspect.getNode(): " + (parameter.getNode() == (suspect == null ? null : suspect.getNode())) + "; " + "."; LOG.error(message); return i; }
private void tryToMoveInitializers( PsiMethod constructor, HashSet<PsiMethod> subConstructors, LinkedHashSet<PsiField> movedFields) throws IncorrectOperationException { final LinkedHashMap<PsiField, Initializer> fieldsToInitializers = new LinkedHashMap<PsiField, Initializer>(); boolean anyFound = false; for (PsiField field : movedFields) { PsiStatement commonInitializer = null; final ArrayList<PsiElement> fieldInitializersToRemove = new ArrayList<PsiElement>(); for (PsiMethod subConstructor : subConstructors) { commonInitializer = hasCommonInitializer( commonInitializer, subConstructor, field, fieldInitializersToRemove); if (commonInitializer == null) break; } if (commonInitializer != null) { final ParametersAndMovedFieldsUsedCollector visitor = new ParametersAndMovedFieldsUsedCollector(movedFields); commonInitializer.accept(visitor); fieldsToInitializers.put( field, new Initializer( commonInitializer, visitor.getUsedFields(), visitor.getUsedParameters(), fieldInitializersToRemove)); anyFound = true; } } if (!anyFound) return; { final Set<PsiField> initializedFields = fieldsToInitializers.keySet(); Set<PsiField> unmovable = RefactoringUtil.transitiveClosure( new RefactoringUtil.Graph<PsiField>() { public Set<PsiField> getVertices() { return initializedFields; } public Set<PsiField> getTargets(PsiField source) { return fieldsToInitializers.get(source).movedFieldsUsed; } }, new Condition<PsiField>() { public boolean value(PsiField object) { return !initializedFields.contains(object); } }); for (PsiField psiField : unmovable) { fieldsToInitializers.remove(psiField); } } final PsiElementFactory factory = JavaPsiFacade.getElementFactory(myProject); if (constructor == null) { constructor = (PsiMethod) myTargetSuperClass.add(factory.createConstructor()); final String visibilityModifier = VisibilityUtil.getVisibilityModifier(myTargetSuperClass.getModifierList()); PsiUtil.setModifierProperty(constructor, visibilityModifier, true); } ArrayList<PsiField> initializedFields = new ArrayList<PsiField>(fieldsToInitializers.keySet()); Collections.sort( initializedFields, new Comparator<PsiField>() { public int compare(PsiField field1, PsiField field2) { Initializer i1 = fieldsToInitializers.get(field1); Initializer i2 = fieldsToInitializers.get(field2); if (i1.movedFieldsUsed.contains(field2)) return 1; if (i2.movedFieldsUsed.contains(field1)) return -1; return 0; } }); for (final PsiField initializedField : initializedFields) { Initializer initializer = fieldsToInitializers.get(initializedField); // correct constructor parameters and subConstructors super calls final PsiParameterList parameterList = constructor.getParameterList(); for (final PsiParameter parameter : initializer.usedParameters) { parameterList.add(parameter); } for (final PsiMethod subConstructor : subConstructors) { modifySuperCall(subConstructor, initializer.usedParameters); } PsiStatement assignmentStatement = (PsiStatement) constructor.getBody().add(initializer.initializer); PsiManager manager = PsiManager.getInstance(myProject); ChangeContextUtil.decodeContextInfo( assignmentStatement, myTargetSuperClass, RefactoringChangeUtil.createThisExpression(manager, null)); for (PsiElement psiElement : initializer.statementsToRemove) { psiElement.delete(); } } }
private static void processPrimaryMethod( JavaChangeInfo changeInfo, PsiMethod method, PsiMethod baseMethod, boolean isOriginal) throws IncorrectOperationException { PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory(); if (changeInfo.isVisibilityChanged()) { PsiModifierList modifierList = method.getModifierList(); final String highestVisibility = isOriginal ? changeInfo.getNewVisibility() : VisibilityUtil.getHighestVisibility( changeInfo.getNewVisibility(), VisibilityUtil.getVisibilityModifier(modifierList)); VisibilityUtil.setVisibility(modifierList, highestVisibility); } if (changeInfo.isNameChanged()) { String newName = baseMethod == null ? changeInfo.getNewName() : RefactoringUtil.suggestNewOverriderName( method.getName(), baseMethod.getName(), changeInfo.getNewName()); if (newName != null && !newName.equals(method.getName())) { final PsiIdentifier nameId = method.getNameIdentifier(); assert nameId != null; nameId.replace( JavaPsiFacade.getInstance(method.getProject()) .getElementFactory() .createIdentifier(newName)); } } final PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : ChangeSignatureProcessor.calculateSubstitutor(method, baseMethod); if (changeInfo.isReturnTypeChanged()) { PsiType newTypeElement = changeInfo .getNewReturnType() .getType(changeInfo.getMethod().getParameterList(), method.getManager()); final PsiType returnType = substitutor.substitute(newTypeElement); // don't modify return type for non-Java overriders (EJB) if (method.getName().equals(changeInfo.getNewName())) { final PsiTypeElement typeElement = method.getReturnTypeElement(); if (typeElement != null) { typeElement.replace(factory.createTypeElement(returnType)); } } } PsiParameterList list = method.getParameterList(); PsiParameter[] parameters = list.getParameters(); final JavaParameterInfo[] parameterInfos = changeInfo.getNewParameters(); final int delta = baseMethod != null ? baseMethod.getParameterList().getParametersCount() - method.getParameterList().getParametersCount() : 0; PsiParameter[] newParms = new PsiParameter[Math.max(parameterInfos.length - delta, 0)]; final String[] oldParameterNames = changeInfo.getOldParameterNames(); final String[] oldParameterTypes = changeInfo.getOldParameterTypes(); for (int i = 0; i < newParms.length; i++) { JavaParameterInfo info = parameterInfos[i]; int index = info.getOldIndex(); if (index >= 0) { PsiParameter parameter = parameters[index]; newParms[i] = parameter; String oldName = oldParameterNames[index]; if (!oldName.equals(info.getName()) && oldName.equals(parameter.getName())) { PsiIdentifier newIdentifier = factory.createIdentifier(info.getName()); parameter.getNameIdentifier().replace(newIdentifier); } String oldType = oldParameterTypes[index]; if (!oldType.equals(info.getTypeText())) { parameter.normalizeDeclaration(); PsiType newType = substitutor.substitute( info.createType(changeInfo.getMethod().getParameterList(), method.getManager())); parameter.getTypeElement().replace(factory.createTypeElement(newType)); } } else { newParms[i] = createNewParameter(changeInfo, info, substitutor); } } resolveParameterVsFieldsConflicts(newParms, method, list, changeInfo.toRemoveParm()); fixJavadocsForChangedMethod(method, changeInfo, newParms.length); if (changeInfo.isExceptionSetOrOrderChanged()) { final PsiClassType[] newExceptions = getPrimaryChangedExceptionInfo(changeInfo); fixPrimaryThrowsLists(method, newExceptions); } }
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); } }); }
public List<PsiParameter> getChildren(PsiParameterList psiParameterList) { return Arrays.asList(psiParameterList.getParameters()); }