ConversionService prevents Converter from trying to convert to a subtype of its actual target type (SPR-8718)
This commit is contained in:
@@ -428,6 +428,10 @@ public class GenericConversionService implements ConversionService, ConverterReg
|
||||
return Collections.singleton(this.typeInfo);
|
||||
}
|
||||
|
||||
public boolean matchesTargetType(TypeDescriptor targetType) {
|
||||
return this.typeInfo.getTargetType().equals(targetType.getObjectType());
|
||||
}
|
||||
|
||||
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
|
||||
if (source == null) {
|
||||
return convertNullSource(sourceType, targetType);
|
||||
@@ -498,6 +502,12 @@ public class GenericConversionService implements ConversionService, ConverterReg
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.defaultConverter instanceof ConverterAdapter) {
|
||||
ConverterAdapter adapter = (ConverterAdapter) this.defaultConverter;
|
||||
if (!adapter.matchesTargetType(targetType)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return this.defaultConverter;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
package org.springframework.core.convert.support;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.SystemColor;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -138,6 +140,18 @@ public class GenericConversionServiceTests {
|
||||
assertEquals(new Integer(3), result);
|
||||
}
|
||||
|
||||
// SPR-8718
|
||||
|
||||
@Test(expected=ConverterNotFoundException.class)
|
||||
public void convertSuperTarget() {
|
||||
conversionService.addConverter(new ColorConverter());
|
||||
conversionService.convert("#000000", SystemColor.class).getClass();
|
||||
}
|
||||
|
||||
public class ColorConverter implements Converter<String, Color> {
|
||||
public Color convert(String source) { if (!source.startsWith("#")) source = "#" + source; return Color.decode(source); }
|
||||
}
|
||||
|
||||
@Test
|
||||
public void convertObjectToPrimitive() {
|
||||
assertFalse(conversionService.canConvert(String.class, boolean.class));
|
||||
|
||||
Reference in New Issue
Block a user