Skip to content

Commit

Permalink
Ignore mutable static fields annotated with @SuppressWarnings
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek committed Oct 13, 2024
1 parent 5ca981f commit 243bd20
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
"""
)
);
}
}

0 comments on commit 243bd20

Please sign in to comment.