Skip to content

Commit

Permalink
try to rewrite method references
Browse files Browse the repository at this point in the history
  • Loading branch information
holgpar committed May 1, 2024
1 parent dda4fa4 commit 038637c
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,28 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
);
}

@Override
public J.MemberReference visitMemberReference(J.MemberReference memberReference, ExecutionContext ctx) {
// when "memberReference" is "a::getTest"
// memberReference.getMethodType() == null
JavaType.Method methodType = memberReference.getMethodType();
if(methodType == null) {
return memberReference;
}

JavaType.FullyQualified declaringType = methodType.getDeclaringType();
String methodName = methodType.getName();
String classFqn = declaringType.getFullyQualifiedName();
if(recordTypeToMembers.containsKey(classFqn)
&& recordTypeToMembers.get(classFqn).contains(getterMethodNameToFluentMethodName(methodName))
&& methodName.startsWith(STANDARD_GETTER_PREFIX)) {
return memberReference.withMethodType(methodType.withName(getterMethodNameToFluentMethodName(methodName)));
}

return memberReference;
}


private boolean isMethodInvocationOnRecordTypeClassMember(J.MethodInvocation methodInvocation) {
Expression expression = methodInvocation.getSelect();
if (!isClassExpression(expression)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import org.openrewrite.test.RewriteTest;
import org.openrewrite.test.TypeValidation;

import java.util.function.Supplier;

import static org.openrewrite.java.Assertions.*;

class LombokValueToRecordTest implements RewriteTest {
Expand Down Expand Up @@ -243,6 +245,76 @@ public record A(
);
}

public static class A {
String test;

public String getTest() {
return test;
}
}
@Test
@Issue("https://github.com/openrewrite/rewrite-migrate-java/issues/449")
void methodReferences() {

var a = new A();

//language=java
rewriteRun(
s -> s.typeValidationOptions(TypeValidation.none()),
java(
"""
package example;
import lombok.Value;
import java.util.function.Supplier;
@Value
public class A {
String test;
}
class B {
public static String classMethod() {
return "foo";
}
}
class Using {
Supplier<String> usingMethodReference() {
A a = new A("foo");
return a::getTest;
}
}
""",
"""
package example;
import java.util.function.Supplier;
public record A(
String test) {
}
class Using {
Supplier<String> usingMethodReference() {
A a = new A("foo");
return a::test;
}
}
"""
)
);

}

@Nested
class Unchanged {
@Test
Expand Down

0 comments on commit 038637c

Please sign in to comment.