diff --git a/rewrite-java-test/src/test/java/org/openrewrite/java/cleanup/FinalizePrivateFieldsTest.java b/rewrite-java-test/src/test/java/org/openrewrite/java/cleanup/FinalizePrivateFieldsTest.java index 31184f44e9e..b9de7ff6f63 100644 --- a/rewrite-java-test/src/test/java/org/openrewrite/java/cleanup/FinalizePrivateFieldsTest.java +++ b/rewrite-java-test/src/test/java/org/openrewrite/java/cleanup/FinalizePrivateFieldsTest.java @@ -304,6 +304,26 @@ class A { ); } + @Test + void fieldReferencedByNonModifyingUnaryOperator() { + rewriteRun( + java( + """ + class A { + private int i = 42; + private int j = -i; + } + """, + """ + class A { + private final int i = 42; + private final int j = -i; + } + """ + ) + ); + } + @Disabled ("Doesn't support multiple constructors, to be enhanced") @Test void fieldAssignedInAllAlternateConstructors() { diff --git a/rewrite-java/src/main/java/org/openrewrite/java/cleanup/FinalizePrivateFields.java b/rewrite-java/src/main/java/org/openrewrite/java/cleanup/FinalizePrivateFields.java index 906e91a9b7d..328bd8b5f2e 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/cleanup/FinalizePrivateFields.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/cleanup/FinalizePrivateFields.java @@ -140,7 +140,9 @@ public J.AssignmentOperation visitAssignmentOperation(J.AssignmentOperation assi @Override public J.Unary visitUnary(J.Unary unary, Map assignedCountMap) { J.Unary u = super.visitUnary(unary, assignedCountMap); - updateAssignmentCount(getCursor(), u.getExpression(),assignedCountMap); + if (u.getOperator().isModifying()) { + updateAssignmentCount(getCursor(), u.getExpression(), assignedCountMap); + } return u; }