Skip to content

ConversionService.canConvert(..) is inconsistent with the behavior of ConversionService.convert(..) method. [SPR-7548] #12205

@spring-projects-issues

Description

@spring-projects-issues

Oleg Zhurakousky opened SPR-7548 and commented

This might actually be a bug, but for now i am treating it as an improvement request.

Basically there are couple of scenarios when canConvert(..) method could return 'false' while the actual conversion is still possible.
For example conversion of an empty parameterized or un-parameterized collection to a collection parameterized with different type or even unparameterized collection.

A more realistic scenario is when using SpEL to invoke method with parameterized collection as argument while passing differently parameterized or un-parameterized but EMPTY collection.
See code below

private static class MethodWithCollection{
	public void methodWithCollection(List<Foo> fooCollection){}
}
// test code
List<Bar> emptyArray = new ArrayList<Bar>();
MethodParameter methodParam = new MethodParameter(MethodWithCollection.class.getDeclaredMethod("methodWithCollection", List.class), 0);
GenericConversionService conversionService = ConversionServiceFactory.createDefaultConversionService();
boolean canConvert = conversionService.canConvert(emptyArray, new TypeDescriptor(methodParam));.

The above will actually return FALSE
However, if you still decide to continue with conversion it will happen successfully:

Object convertedA = conversionService.convert(emptyArray, TypeDescriptor.forObject(emptyArray), new TypeDescriptor(methodParam));

It will simply return an empty unconverted collection and rightfully so since empty collection is unconvertible and no attempt to convert it should be made.. In fact I believe this is closely related to the recent change in #12146.

So as you can see there is inconsistency between canConvert(..) and convert(..) methods

Unfortunately today there is no way for the _ConversionService.canConvert(..) method to know wether we are dealing with en empty collection or not since there is no method that takes the source object as an argument, only source type.

So I would propose to add a new method to a ConversionService

boolean canConvert(Object source, TypeDescriptor targetType);

as well as few extra modifications to accommodate the above scenario.

Attached is a patch which takes care of this issue with additional test cases. It passes full Spring build.


Affects: 3.0.4

Attachments:

Issue Links:

Referenced from: commits spring-projects/spring-integration@4263202

1 votes, 5 watchers

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: declinedA suggestion or change that we don't feel we should currently applytype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions