Skip to content

Commit bdac8e0

Browse files
authored
Add imports for static methods from the same package (#6433)
* Add imports for static methods from the same package * Only add import if member of different class * Reorder to minimize the implementation
1 parent 89ba2da commit bdac8e0

2 files changed

Lines changed: 50 additions & 1 deletion

File tree

rewrite-java-test/src/test/java/org/openrewrite/java/UseStaticImportTest.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,4 +459,45 @@ void test() {
459459
)
460460
);
461461
}
462+
463+
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/798")
464+
@Test
465+
void shouldAddStaticImportForSamePackageMethod() {
466+
rewriteRun(
467+
spec -> spec.recipe(new UseStaticImport("de..* *(..)")),
468+
java(
469+
"""
470+
package de;
471+
472+
public class ClassB {
473+
public static String getSomething() {
474+
return "something";
475+
}
476+
}
477+
"""
478+
),
479+
java(
480+
"""
481+
package de;
482+
483+
public class ClassA {
484+
static void methodA() {
485+
System.out.println(ClassB.getSomething());
486+
}
487+
}
488+
""",
489+
"""
490+
package de;
491+
492+
import static de.ClassB.getSomething;
493+
494+
public class ClassA {
495+
static void methodA() {
496+
System.out.println(getSomething());
497+
}
498+
}
499+
"""
500+
)
501+
);
502+
}
462503
}

rewrite-java/src/main/java/org/openrewrite/java/AddImport.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,15 @@ public AddImport(@Nullable String packageName, String typeName, @Nullable String
114114
// Nor if the classes are within the same package
115115
if (!"Record".equals(typeName) && cu.getPackageDeclaration() != null &&
116116
packageName.equals(cu.getPackageDeclaration().getExpression().printTrimmed(getCursor()))) {
117-
return cu;
117+
// For static imports, only skip if the target type is declared in this compilation unit
118+
if (member == null) {
119+
return cu;
120+
}
121+
for (J.ClassDeclaration clazz : cu.getClasses()) {
122+
if (TypeUtils.isOfClassType(clazz.getType(), fullyQualifiedName)) {
123+
return cu;
124+
}
125+
}
118126
}
119127
Optional<JavaType> typeReference = findTypeReference(cu);
120128
if (onlyIfReferenced && !typeReference.isPresent()) {

0 commit comments

Comments
 (0)