Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

import static org.openrewrite.java.tree.J.ClassDeclaration.Kind.Type.Interface;
Expand Down Expand Up @@ -79,6 +80,14 @@ public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration cs, Execution
.anyMatch(methodDeclaration -> methodMatcher.matches(methodDeclaration, classDecl))) {
return classDecl;
}
// If a superclass already provides the method, don't add it.
JavaType.FullyQualified supertype = classDecl.getType() != null ? classDecl.getType().getSupertype() : null;
while (supertype != null) {
if (supertype.getMethods().stream().anyMatch(methodMatcher::matches)) {
return classDecl;
}
supertype = supertype.getSupertype();
}

return classDecl.withBody(JavaTemplate.builder(methodTemplateString)
.build()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,22 @@ protected void m1() {
);
}

@Test
void skipWhenSuperclassAlreadyHasMethod() {
//language=java
rewriteRun(
java(
"""
interface I1 {}
class SuperClass implements I1 {
public void m1() {
System.out.println("m1 from super");
}
}
class SubClass extends SuperClass {}
"""
)
);
}

}
Loading