diff --git a/src/main/java/org/openrewrite/java/migrate/lang/var/DeclarationCheck.java b/src/main/java/org/openrewrite/java/migrate/lang/var/DeclarationCheck.java index cc8bb8b02e..d1b08c01fb 100644 --- a/src/main/java/org/openrewrite/java/migrate/lang/var/DeclarationCheck.java +++ b/src/main/java/org/openrewrite/java/migrate/lang/var/DeclarationCheck.java @@ -15,11 +15,11 @@ */ package org.openrewrite.java.migrate.lang.var; -import static java.util.Objects.requireNonNull; - import org.openrewrite.Cursor; import org.openrewrite.java.tree.*; +import static java.util.Objects.requireNonNull; + final class DeclarationCheck { private DeclarationCheck() { @@ -37,14 +37,11 @@ private DeclarationCheck() { * @return true if var is applicable in general */ public static boolean isVarApplicable(Cursor cursor, J.VariableDeclarations vd) { - boolean isMethodParameter = DeclarationCheck.isMethodParameter(vd, cursor); - boolean isMultiVarDefinition = !DeclarationCheck.isSingleVariableDefinition(vd); - boolean useTernary = DeclarationCheck.initializedByTernary(vd); - if (isMethodParameter || isMultiVarDefinition || useTernary) return false; - - boolean isInsideMethod = DeclarationCheck.isInsideMethod(cursor); - boolean isInsideInitializer = DeclarationCheck.isInsideInitializer(cursor, 0); - return isInsideMethod || isInsideInitializer; + if (isField(vd, cursor) || isMethodParameter(vd, cursor) || !isSingleVariableDefinition(vd) || initializedByTernary(vd)) { + return false; + } + + return isInsideMethod(cursor) || isInsideInitializer(cursor, 0); } /** @@ -140,6 +137,15 @@ private static boolean isInsideMethod(Cursor cursor) { return isNotRoot && isNotClassDeclaration && isMethodDeclaration; } + private static boolean isField(J.VariableDeclarations vd, Cursor cursor) { + Cursor parent = cursor.getParentTreeCursor(); + if (parent.getParent() == null) { + return false; + } + Cursor grandparent = parent.getParentTreeCursor(); + return parent.getValue() instanceof J.Block && (grandparent.getValue() instanceof J.ClassDeclaration || grandparent.getValue() instanceof J.NewClass); + } + /** * Determine if the variable declaration at hand is part of a method declaration * diff --git a/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForObject.java b/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForObject.java index b2f7d7ee10..60a1729b19 100644 --- a/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForObject.java +++ b/src/main/java/org/openrewrite/java/migrate/lang/var/UseVarForObject.java @@ -64,7 +64,7 @@ static final class UseVarForObjectVisitor extends JavaIsoVisitor