[java-intentions] BindFieldsFromParameters: disable for existing field if static or type doesn't match

GitOrigin-RevId: ad1d93533626f5e76a3f53c5ab25b06a5aa07f1e
This commit is contained in:
Tagir Valeev
2024-09-10 17:41:50 +02:00
committed by intellij-monorepo-bot
parent 0f2865b919
commit 9092a09789
3 changed files with 39 additions and 8 deletions

View File

@@ -269,21 +269,29 @@ public final class FieldFromParameterUtils {
return isAvailable(myParameter, type, targetClass, true); return isAvailable(myParameter, type, targetClass, true);
} }
public static boolean isAvailable(@NotNull PsiParameter myParameter, public static boolean isAvailable(@NotNull PsiParameter parameter,
@Nullable PsiType type, @Nullable PsiType type,
@Nullable PsiClass targetClass, @Nullable PsiClass targetClass,
boolean findIndirectAssignments) { boolean findIndirectAssignments) {
if (!myParameter.isValid() || if (!parameter.isValid() ||
!BaseIntentionAction.canModify(myParameter) || !BaseIntentionAction.canModify(parameter) ||
!(myParameter.getDeclarationScope() instanceof PsiMethod method)) { !(parameter.getDeclarationScope() instanceof PsiMethod method)) {
return false; return false;
} }
if (type == null || targetClass == null || !type.isValid()) {
return false;
}
PsiField existingField = targetClass.findFieldByName(parameter.getName(), true);
if (existingField != null) {
if (!existingField.getType().isAssignableFrom(type) ||
method.hasModifierProperty(PsiModifier.STATIC) != existingField.hasModifierProperty(PsiModifier.STATIC) ||
existingField.hasModifierProperty(PsiModifier.FINAL) && !method.isConstructor()) {
return false;
}
}
return method.getBody() != null && return method.getBody() != null &&
type != null &&
type.isValid() &&
targetClass != null &&
!targetClass.isInterface() && !targetClass.isInterface() &&
(!targetClass.isRecord() || method.hasModifierProperty(PsiModifier.STATIC)) && (!targetClass.isRecord() || method.hasModifierProperty(PsiModifier.STATIC)) &&
getParameterAssignedToField(myParameter, findIndirectAssignments) == null; getParameterAssignedToField(parameter, findIndirectAssignments) == null;
} }
} }

View File

@@ -0,0 +1,12 @@
// "Bind method parameters to fields" "true-preview"
class Bar {
private static int f4;
private int f1;
private static boolean f2;
private static final int f3 = 123;
static void test(int f1, int f2, int f3, int f4) {
Bar.f4 = f4;
}
}

View File

@@ -0,0 +1,11 @@
// "Bind method parameters to fields" "true-preview"
class Bar {
private int f1;
private static boolean f2;
private static final int f3 = 123;
static void <caret>test(int f1, int f2, int f3, int f4) {
}
}