From 243bd2008aef26a0981c729e7288ba408e6fa41f Mon Sep 17 00:00:00 2001 From: Tim te Beek Date: Sun, 13 Oct 2024 18:13:19 +0200 Subject: [PATCH] Ignore mutable static fields annotated with `@SuppressWarnings` --- .../recipes/NoMutableStaticFieldsInRecipes.java | 5 ++++- .../NoMutableStaticFieldsInRecipesTest.java | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/rewrite-java/src/main/java/org/openrewrite/java/recipes/NoMutableStaticFieldsInRecipes.java b/rewrite-java/src/main/java/org/openrewrite/java/recipes/NoMutableStaticFieldsInRecipes.java index 1fea29c61e8..e04b14addbb 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/recipes/NoMutableStaticFieldsInRecipes.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/recipes/NoMutableStaticFieldsInRecipes.java @@ -21,6 +21,7 @@ import org.openrewrite.TreeVisitor; import org.openrewrite.internal.ListUtils; import org.openrewrite.java.JavaIsoVisitor; +import org.openrewrite.java.search.FindAnnotations; import org.openrewrite.java.search.UsesType; import org.openrewrite.java.tree.J; import org.openrewrite.java.tree.TypeUtils; @@ -48,7 +49,9 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, Ex return cd.withBody(cd.getBody().withStatements(ListUtils.map(cd.getBody().getStatements(), stmt -> { if (stmt instanceof J.VariableDeclarations) { J.VariableDeclarations field = (J.VariableDeclarations) stmt; - if (field.hasModifier(J.Modifier.Type.Static) && !field.hasModifier(J.Modifier.Type.Final)) { + if (field.hasModifier(J.Modifier.Type.Static) && + !field.hasModifier(J.Modifier.Type.Final) && + FindAnnotations.find(field, "@java.lang.SuppressWarnings").isEmpty()) { // We want to discourage the use of mutable static fields in recipes, // so rather than make them immutable, we'll just remove the field. // Any fields that were intended as constants should be made final. diff --git a/rewrite-java/src/test/java/org/openrewrite/java/recipes/NoMutableStaticFieldsInRecipesTest.java b/rewrite-java/src/test/java/org/openrewrite/java/recipes/NoMutableStaticFieldsInRecipesTest.java index 35f52dab425..a7612e1606c 100644 --- a/rewrite-java/src/test/java/org/openrewrite/java/recipes/NoMutableStaticFieldsInRecipesTest.java +++ b/rewrite-java/src/test/java/org/openrewrite/java/recipes/NoMutableStaticFieldsInRecipesTest.java @@ -71,4 +71,21 @@ public class A { ) ); } + + @Test + void retainWhenWarningsSuppressed() { + rewriteRun( + java( + """ + import org.openrewrite.Recipe; + + public class A extends Recipe { + static final int immutable = 0; + @SuppressWarnings("unused") + static int mutable = 0; + } + """ + ) + ); + } }