Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support record canonical constructor in BeanUtils #33707

Closed
wants to merge 1 commit into from
Closed
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 java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.RecordComponent;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
Expand Down Expand Up @@ -252,6 +253,19 @@ else if (ctors.length == 0) {
return (Constructor<T>) ctors[0];
}
}
else if (clazz.isRecord()) {
try {
// if record -> use canonical constructor, which is always presented
Class<?>[] paramTypes
= Arrays.stream(clazz.getRecordComponents())
.map(RecordComponent::getType)
.toArray(Class<?>[]::new);
return clazz.getDeclaredConstructor(paramTypes);
}
catch (NoSuchMethodException ex) {
// Giving up with record...
}
}

// Several constructors -> let's try to take the default constructor
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -521,10 +521,26 @@ void isNotSimpleProperty(Class<?> type) {
assertThat(BeanUtils.isSimpleProperty(type)).as("Type [" + type.getName() + "] should not be a simple property").isFalse();
}

@Test
void resolveRecordConstructor() throws NoSuchMethodException {
assertThat(BeanUtils.getResolvableConstructor(RecordWithMultiplePublicConstructors.class))
.isEqualTo(getRecordWithMultipleVariationsConstructor());
}

private void assertSignatureEquals(Method desiredMethod, String signature) {
assertThat(BeanUtils.resolveSignature(signature, MethodSignatureBean.class)).isEqualTo(desiredMethod);
}

public record RecordWithMultiplePublicConstructors(String value, String name) {
public RecordWithMultiplePublicConstructors(String value) {
this(value, "default value");
}
}

private Constructor<RecordWithMultiplePublicConstructors> getRecordWithMultipleVariationsConstructor() throws NoSuchMethodException {
return RecordWithMultiplePublicConstructors.class.getConstructor(String.class, String.class);
}


@SuppressWarnings("unused")
private static class NumberHolder {
Expand Down