diff --git a/src/main/java/org/openrewrite/staticanalysis/UseLambdaForFunctionalInterface.java b/src/main/java/org/openrewrite/staticanalysis/UseLambdaForFunctionalInterface.java index a2eff4a38..a0f874070 100644 --- a/src/main/java/org/openrewrite/staticanalysis/UseLambdaForFunctionalInterface.java +++ b/src/main/java/org/openrewrite/staticanalysis/UseLambdaForFunctionalInterface.java @@ -61,6 +61,15 @@ public Duration getEstimatedEffortPerOccurrence() { @Override public TreeVisitor getVisitor() { return Repeat.repeatUntilStable(new JavaVisitor() { + @Override + public J visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext ctx) { + // Don't convert anonymous classes to lambdas when located in an enum class, to avoid `Accessing static field from enum constructor is not allowed` errors. + if (classDecl.getKind() == J.ClassDeclaration.Kind.Type.Enum) { + return classDecl; + } + return super.visitClassDeclaration(classDecl, ctx); + } + @Override public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) { J.NewClass n = (J.NewClass) super.visitNewClass(newClass, ctx); diff --git a/src/test/java/org/openrewrite/staticanalysis/UseLambdaForFunctionalInterfaceTest.java b/src/test/java/org/openrewrite/staticanalysis/UseLambdaForFunctionalInterfaceTest.java index 13b9d3007..94fa0cebe 100644 --- a/src/test/java/org/openrewrite/staticanalysis/UseLambdaForFunctionalInterfaceTest.java +++ b/src/test/java/org/openrewrite/staticanalysis/UseLambdaForFunctionalInterfaceTest.java @@ -774,4 +774,60 @@ public List call() { ) ); } + + @Test + @Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/413") + void dontUseLambdaWhenEnumAccessesStaticFieldFromConstructor() { + rewriteRun( + //language=java + java( + """ + import java.time.LocalDate; + import java.time.format.DateTimeFormatter; + enum Test { + A, B; + + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + Test() { + Runnable r = new Runnable() { + @Override + public void run() { + DATE_FORMAT.format(LocalDate.now()); + } + }; + } + } + """ + ) + ); + } + + @Test + @Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/413") + void dontUseLambdaWhenEnumAccessesStaticFieldFromFromMethod() { + rewriteRun( + //language=java + java( + """ + import java.time.LocalDate; + import java.time.format.DateTimeFormatter; + enum Test { + A, B; + + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + void test() { + Runnable r = new Runnable() { + @Override + public void run() { + DATE_FORMAT.format(LocalDate.now()); + } + }; + } + } + """ + ) + ); + } }