Skip to content

Commit 5f18964

Browse files
authored
Skip UseEnumSetOf empty conversion for static fields to avoid circular class-init (#1157) (#1161)
* Skip UseEnumSetOf empty conversion for static fields to avoid circular class-init (#1157) * Prevent conversion of empty Set.of() in static fields Skip conversion for empty Set.of() in static field initializers to avoid ClassCastException.
1 parent 4cd2123 commit 5f18964

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

src/main/java/org/openrewrite/java/migrate/util/UseEnumSetOf.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,9 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation methodInvocat
7878
}
7979

8080
if (args.get(0) instanceof J.Empty) {
81+
if (isStaticField(parent)) {
82+
return mi;
83+
}
8184
JavaType firstTypeParameter = ((JavaType.Parameterized) type).getTypeParameters().get(0);
8285
JavaType.ShallowClass shallowClass = JavaType.ShallowClass.build(firstTypeParameter.toString());
8386
return JavaTemplate.builder("EnumSet.noneOf(" + shallowClass.getClassName() + ".class)")
@@ -120,6 +123,11 @@ private boolean isAssignmentSetOfEnum(@Nullable JavaType type) {
120123
return false;
121124
}
122125

126+
private boolean isStaticField(Cursor parent) {
127+
return parent.getValue() instanceof J.VariableDeclarations &&
128+
((J.VariableDeclarations) parent.getValue()).hasModifier(J.Modifier.Type.Static);
129+
}
130+
123131
private boolean isArrayParameter(final List<Expression> args) {
124132
if (args.size() != 1) {
125133
return false;

src/test/java/org/openrewrite/java/migrate/util/UseEnumSetOfTest.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,45 @@ public void method() {
182182
);
183183
}
184184

185+
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/1157")
186+
@Test
187+
void dontConvertEmptySetOfInStaticField() {
188+
//language=java
189+
rewriteRun(
190+
java(
191+
"""
192+
package com.helloworld;
193+
194+
import java.util.Set;
195+
196+
public enum ConfigType {
197+
ENUM,
198+
BOOLEAN,
199+
INTEGER;
200+
201+
public static final Set<ConfigProperty> SUBSCRIBE_TO_ALL = Set.<ConfigProperty>of();
202+
}
203+
""",
204+
spec -> spec.markers(javaVersion(25))),
205+
java(
206+
"""
207+
package com.helloworld;
208+
209+
import static com.helloworld.ConfigType.BOOLEAN;
210+
import static com.helloworld.ConfigType.ENUM;
211+
import static com.helloworld.ConfigType.INTEGER;
212+
213+
public enum ConfigProperty {
214+
TRIAL_TYPE(ENUM),
215+
IS_TRIAL_ENABLED(BOOLEAN),
216+
MIN_ACCOUNT_AGE_MINUTES(INTEGER);
217+
218+
ConfigProperty(final ConfigType type) {}
219+
}
220+
""",
221+
spec -> spec.markers(javaVersion(25))));
222+
}
223+
185224
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/958")
186225
@Test
187226
void retainEmptySetOf() {

0 commit comments

Comments
 (0)