Skip to content

Commit

Permalink
UseLambdaForFunctionalInterface recipe should not convert when code…
Browse files Browse the repository at this point in the history
… uses a static field from enum constructor (#415)

* `UseLambdaForFunctionalInterface` recipe should not convert when code uses a static field from enum constructor

* `UseLambdaForFunctionalInterface` recipe should not convert when code uses a static field from enum constructor

* Simplify

---------

Co-authored-by: Tim te Beek <[email protected]>
  • Loading branch information
jevanlingen and timtebeek authored Dec 27, 2024
1 parent 606ef22 commit 237f8b8
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,15 @@ public Duration getEstimatedEffortPerOccurrence() {
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Repeat.repeatUntilStable(new JavaVisitor<ExecutionContext>() {
@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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -774,4 +774,60 @@ public <T> List<T> 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());
}
};
}
}
"""
)
);
}
}

0 comments on commit 237f8b8

Please sign in to comment.