Skip to content

Commit 442d8a6

Browse files
committed
TypeDescriptor properly narrows ResolvableType for non-typed collection elements
Issue: SPR-14971 (cherry picked from commit aef1460)
1 parent 934fffe commit 442d8a6

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ public TypeDescriptor narrow(Object value) {
190190
return this;
191191
}
192192
ResolvableType narrowed = ResolvableType.forType(value.getClass(), getResolvableType());
193-
return new TypeDescriptor(narrowed, null, getAnnotations());
193+
return new TypeDescriptor(narrowed, value.getClass(), getAnnotations());
194194
}
195195

196196
/**
@@ -439,7 +439,10 @@ private TypeDescriptor narrow(Object value, TypeDescriptor typeDescriptor) {
439439
if (typeDescriptor != null) {
440440
return typeDescriptor.narrow(value);
441441
}
442-
return (value != null ? new TypeDescriptor(getResolvableType(), value.getClass(), getAnnotations()) : null);
442+
if (value != null) {
443+
return narrow(value);
444+
}
445+
return null;
443446
}
444447

445448
@Override

spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -627,13 +627,35 @@ public void convertArrayToArrayAssignable() {
627627
assertEquals(3, result[2]);
628628
}
629629

630+
@Test
631+
public void convertListOfNonStringifiable() {
632+
List<Object> list = Arrays.asList(new TestEntity(1L), new TestEntity(2L));
633+
assertTrue(conversionService.canConvert(list.getClass(), String.class));
634+
try {
635+
conversionService.convert(list, String.class);
636+
}
637+
catch (ConversionFailedException ex) {
638+
assertTrue(ex.getMessage().contains(list.getClass().getName()));
639+
assertTrue(ex.getCause() instanceof ConverterNotFoundException);
640+
assertTrue(ex.getCause().getMessage().contains(TestEntity.class.getName()));
641+
}
642+
}
643+
644+
@Test
645+
public void convertListOfStringToString() {
646+
List<String> list = Arrays.asList("Foo", "Bar");
647+
assertTrue(conversionService.canConvert(list.getClass(), String.class));
648+
String result = conversionService.convert(list, String.class);
649+
assertEquals("Foo,Bar", result);
650+
}
651+
630652
@Test
631653
public void convertListOfListToString() {
632654
List<String> list1 = Arrays.asList("Foo", "Bar");
633655
List<String> list2 = Arrays.asList("Baz", "Boop");
634656
List<List<String>> list = Arrays.asList(list1, list2);
657+
assertTrue(conversionService.canConvert(list.getClass(), String.class));
635658
String result = conversionService.convert(list, String.class);
636-
assertNotNull(result);
637659
assertEquals("Foo,Bar,Baz,Boop", result);
638660
}
639661

0 commit comments

Comments
 (0)