Skip to content

Commit

Permalink
Split conditional and add clarifying comments on Record handling
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek committed Dec 15, 2024
1 parent 8972196 commit de84ed1
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ class A {

@Test
void forceImportNoJavaRecord() {
// Add import for a class named `Record`, even within the same package, to avoid conflicts with java.lang.Record
rewriteRun(
spec -> spec.recipe(toRecipe(() -> new AddImport<>("com.acme.bank.Record", null, false))),
//language=java
Expand All @@ -211,6 +212,7 @@ class Foo {

@Test
void notForceImportJavaRecord() {
// Do not add import for java.lang.Record by default
rewriteRun(
spec -> spec.recipe(toRecipe(() -> new AddImport<>("java.lang.Record", null, false))),
//language=java
Expand Down
12 changes: 8 additions & 4 deletions rewrite-java/src/main/java/org/openrewrite/java/AddImport.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,14 @@ public AddImport(@Nullable String packageName, String typeName, @Nullable String
return cu;
}

// No need to add imports if the class to import is in java.lang, or if the classes are within the same package
if (("java.lang".equals(packageName) && StringUtils.isBlank(member)) ||
(!"Record".equals(typeName) && cu.getPackageDeclaration() != null &&
packageName.equals(cu.getPackageDeclaration().getExpression().printTrimmed(getCursor())))) {
// No need to add imports if the class to import is in java.lang
if ("java.lang".equals(packageName) && StringUtils.isBlank(member)) {
return cu;
}
// Nor if the classes are within the same package
if (!"Record".equals(typeName) && // Record's late addition to `java.lang` might conflict with user class
cu.getPackageDeclaration() != null &&
packageName.equals(cu.getPackageDeclaration().getExpression().printTrimmed(getCursor()))) {
return cu;
}

Expand Down

0 comments on commit de84ed1

Please sign in to comment.