1515 */
1616package org .openrewrite .java .testing .junit5 ;
1717
18+ import org .openrewrite .Cursor ;
1819import org .openrewrite .ExecutionContext ;
1920import org .openrewrite .Preconditions ;
2021import org .openrewrite .Recipe ;
2728import org .openrewrite .java .tree .J .Modifier .Type ;
2829
2930import java .time .Duration ;
31+ import java .util .Iterator ;
3032
3133public class TempDirNonFinal extends Recipe {
3234
@@ -53,7 +55,7 @@ private static class TempDirVisitor extends JavaIsoVisitor<ExecutionContext> {
5355 public J .VariableDeclarations visitVariableDeclarations (J .VariableDeclarations multiVariable , ExecutionContext ctx ) {
5456 J .VariableDeclarations varDecls = super .visitVariableDeclarations (multiVariable , ctx );
5557 if (varDecls .getLeadingAnnotations ().stream ().anyMatch (TEMPDIR_ANNOTATION_MATCHER ::matches )
56- && varDecls .hasModifier (Type .Final )) {
58+ && varDecls .hasModifier (Type .Final ) && isField ( getCursor ()) ) {
5759 return maybeAutoFormat (varDecls , varDecls .withModifiers (ListUtils
5860 .map (varDecls .getModifiers (), modifier -> modifier .getType () == Type .Final ? null : modifier )),
5961 ctx , getCursor ().getParentOrThrow ());
@@ -62,6 +64,21 @@ public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations m
6264 }
6365 }
6466
67+ // copied from org.openrewrite.java.search.FindFieldsOfType.isField(Cursor), should probably become part of the API
68+ private static boolean isField (Cursor cursor ) {
69+ Iterator <Object > path = cursor .getPath ();
70+ while (path .hasNext ()) {
71+ Object o = path .next ();
72+ if (o instanceof J .MethodDeclaration ) {
73+ return false ;
74+ }
75+ if (o instanceof J .ClassDeclaration ) {
76+ return true ;
77+ }
78+ }
79+ return true ;
80+ }
81+
6582 @ Override
6683 public Duration getEstimatedEffortPerOccurrence () {
6784 return Duration .ofMinutes (1 );
0 commit comments