Uploaded image for project: 'Spring Framework'
  1. Spring Framework
  2. SPR-9257

Resolve Collection element types during conversion

    Details

    • Last commented by a User:
      true

      Description

      Between 3.0 and 3.1 the behavior of TypeDescriptor.forObject changed.
      If the value is a map or a collection then elementTypeDescriptor, mapKeyTypeDescriptor, and mapValueTypeDescriptor remain uninitialized.
      This in turn precludes conversions from happening.

      Our application has a method that accepts a Map where the key is an enum type.
      In 3.0.x we received a map where keys were enums, in 3.1 the keys are strings.

      I'm attaching an updated revision of TypeDescriptor, only the method TypeDescriptor.forObject was changed.
      It used to be:

      	public static TypeDescriptor forObject(Object source) {
      		return (source != null ? valueOf(source.getClass()) : null);
      	}
      

      I changed it to:

          public static TypeDescriptor forObject(Object source) {
              if (source == null) {
                  return null;
              }
              else if (source instanceof Collection<?>) {
                  Class<?> elementType = CollectionUtils.findCommonElementType((Collection<?>)source);
                  return new TypeDescriptor(source.getClass(), elementType==null ? null : new TypeDescriptor(elementType));
              }
              else if (source instanceof Map<?, ?>) {
                  Class<?> keyType = CollectionUtils.findCommonElementType(((Map<?, ?>) source).keySet());
                  Class<?> valueType = CollectionUtils.findCommonElementType(((Map<?, ?>) source).values());
                  return new TypeDescriptor(source.getClass(),
                          keyType==null ? null : new TypeDescriptor(keyType), 
                          valueType==null ? null : new TypeDescriptor(valueType));
              }
              else {
                  return valueOf(source.getClass());
              }
          }
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                pwebb Phil Webb
                Reporter:
                alex322 Sandu Turcan
                Last updater:
                Chris Beams
              • Votes:
                1 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved:
                  Days since last comment:
                  5 years, 47 weeks, 2 days ago