Skip to content

Commit 514d600

Browse files
EugeneNiksdeleuze
authored andcommitted
Support record canonical constructor in BeanUtils
See gh-33707
1 parent 161d399 commit 514d600

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

spring-beans/src/main/java/org/springframework/beans/BeanUtils.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import java.lang.reflect.InvocationTargetException;
2424
import java.lang.reflect.Method;
2525
import java.lang.reflect.Modifier;
26+
import java.lang.reflect.RecordComponent;
2627
import java.lang.reflect.Type;
2728
import java.util.Arrays;
2829
import java.util.Collections;
@@ -252,6 +253,19 @@ else if (ctors.length == 0) {
252253
return (Constructor<T>) ctors[0];
253254
}
254255
}
256+
else if (clazz.isRecord()) {
257+
try {
258+
// if record -> use canonical constructor, which is always presented
259+
Class<?>[] paramTypes
260+
= Arrays.stream(clazz.getRecordComponents())
261+
.map(RecordComponent::getType)
262+
.toArray(Class<?>[]::new);
263+
return clazz.getDeclaredConstructor(paramTypes);
264+
}
265+
catch (NoSuchMethodException ex) {
266+
// Giving up with record...
267+
}
268+
}
255269

256270
// Several constructors -> let's try to take the default constructor
257271
try {

spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,10 +521,26 @@ void isNotSimpleProperty(Class<?> type) {
521521
assertThat(BeanUtils.isSimpleProperty(type)).as("Type [" + type.getName() + "] should not be a simple property").isFalse();
522522
}
523523

524+
@Test
525+
void resolveRecordConstructor() throws NoSuchMethodException {
526+
assertThat(BeanUtils.getResolvableConstructor(RecordWithMultiplePublicConstructors.class))
527+
.isEqualTo(getRecordWithMultipleVariationsConstructor());
528+
}
529+
524530
private void assertSignatureEquals(Method desiredMethod, String signature) {
525531
assertThat(BeanUtils.resolveSignature(signature, MethodSignatureBean.class)).isEqualTo(desiredMethod);
526532
}
527533

534+
public record RecordWithMultiplePublicConstructors(String value, String name) {
535+
public RecordWithMultiplePublicConstructors(String value) {
536+
this(value, "default value");
537+
}
538+
}
539+
540+
private Constructor<RecordWithMultiplePublicConstructors> getRecordWithMultipleVariationsConstructor() throws NoSuchMethodException {
541+
return RecordWithMultiplePublicConstructors.class.getConstructor(String.class, String.class);
542+
}
543+
528544

529545
@SuppressWarnings("unused")
530546
private static class NumberHolder {

0 commit comments

Comments
 (0)