Java: create constant from usage when non-constant is not compilable (IDEA-337261)

GitOrigin-RevId: 5be5a1c196902431a582768fbc461d0d09b14aac
This commit is contained in:
Bas Leijdekkers
2023-11-06 10:45:25 +01:00
committed by intellij-monorepo-bot
parent af5817d1e3
commit b3d096b7fc
4 changed files with 28 additions and 1 deletions

View File

@@ -117,7 +117,7 @@ private class CreateFieldRequests(val myRef: PsiReferenceExpression) {
modifiers = modifiers,
reference = myRef,
useAnchor = ownerClass != null && PsiTreeUtil.isAncestor(target.toJavaClassOrNull(), ownerClass, false),
isConstant = false
isConstant = shouldCreateConstant(myRef)
)
addRequest(target, request)
}
@@ -144,3 +144,7 @@ private fun shouldCreateFinalField(ref: PsiReferenceExpression, targetClass: Jvm
val javaClass = targetClass.toJavaClassOrNull() ?: return false
return CreateFieldFromUsageFix.shouldCreateFinalMember(ref, javaClass)
}
private fun shouldCreateConstant(ref: PsiReferenceExpression): Boolean {
val parent = PsiTreeUtil.skipParentsOfType(ref, PsiExpression::class.java)
return parent is PsiNameValuePair || parent is PsiCaseLabelElementList || parent is PsiAnnotationMethod;
}

View File

@@ -0,0 +1,12 @@
// "Create constant field 'constant'" "true-preview"
class A {
private static final int constant = ;
void x(int i) {
switch (i) {
case constant:
}
}
}

View File

@@ -0,0 +1,10 @@
// "Create constant field 'constant'" "true-preview"
class A {
void x(int i) {
switch (i) {
case constant<caret>:
}
}
}

View File

@@ -23,6 +23,7 @@ import java.io.IOException;
public class CreateFieldFromUsageTest extends LightQuickFixTestCase {
public void testSwitchCaseLabel() { doSingleTest(); }
public void testAnonymousClass() { doSingleTest(); }
public void testExpectedTypes() { doSingleTest(); }
public void testInterface() { doSingleTest(); }