Skip to content

Allow MapToMap conversion even without a default constructor [SPR-9284] #13922

@spring-projects-issues

Description

@spring-projects-issues

Sandu Turcan opened SPR-9284 and commented

We use a thirdparty library which has a class that happens to extend java.util.Properties.
When assigning an instance of this class to a property, MapToMapConverter tries to create a new instance, copy all the entries, and if none of the keys or values were converted returns the original value.
The problem is that in this particular case the default constructor fails to create the throwaway instance.
I changed the convert method to the following:

public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
    if (source == null) {
        return null;
    }
    boolean copyRequired = !targetType.getType().isInstance(source);
    Map<Object, Object> sourceMap = (Map<Object, Object>) source;
    if (!copyRequired && (sourceMap.isEmpty() || targetType.equals(sourceType))) {
        return sourceMap;
    }
    Map<Object, Object> targetMap = CollectionFactory.createMap(targetType.getType(), sourceMap.size());
    for (Map.Entry<Object, Object> entry : sourceMap.entrySet()) {
        Object sourceKey = entry.getKey();
        Object sourceValue = entry.getValue();
        Object targetKey = convertKey(sourceKey, sourceType, targetType.getMapKeyTypeDescriptor());
        Object targetValue = convertValue(sourceValue, sourceType, targetType.getMapValueTypeDescriptor());
        targetMap.put(targetKey, targetValue);
        if (sourceKey != targetKey || sourceValue != targetValue) {
            copyRequired = true;
        }
    }
    return (copyRequired ? targetMap : sourceMap);
}

The actual change:

if (!copyRequired && (sourceMap.isEmpty() || targetType.equals(sourceType))) {

Sub-tasks:

Issue Links:

Referenced from: commits 3f1fb4e, 38c4393, e3136e6

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)type: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions