Announcement Announcement Module
Collapse
No announcement yet.
Converting to generic collections Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Converting to generic collections

    Hi all,
    I'm trying to use the new Converter SPI to convert from ClassA to List<ClassB>. I have a following Converter:

    Code:
    public class ClassAToListOfClassB implements Converter<ClassA, List<ClassB>> {
        public List<ClassB> convert(ClassA source) {
            List<ClassB> list = new ArrayList<ClassB>();
            // convert
            return list;
    }
    But I didn't find a way how to call the converterService.convert() method. The second input parameter is either Class targetType which I can't get for List<ClassB> or TypeDescriptor which I can't get either.

    Later I realized that this is probably wrong approach. I probably need to implement something like org.springframework.core.convert.support.ObjectToC ollectionConverter. So I went ahead and created:

    Code:
    public class ClassAToCollectionOfClassB implements ConditionalGenericConverter
    {
    	private ConversionService conversionService;
    
    	public ClassAToCollectionOfClassB(ConversionService conversionService)
    	{
    		this.conversionService = conversionService;
    	}
    
    	public Set<ConvertiblePair> getConvertibleTypes()
    	{
    		return Collections.singleton(new ConvertiblePair(ClassA.class, Collection.class));
    	}
    
    	public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType)
    	{
    		return targetType.getElementTypeDescriptor().getType().equals(ClassB.class);
    	}
    
    	public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType)
    	{
    		if (source == null) return null;
    		ClassA classA = (ClassA) source;
    
    		Collection target = CollectionFactory.createCollection(targetType.getType(), classA.size());
    
    		final Iterator<ClassA.Row> rowIterator = classA.iterator();
    		while (rowIterator.hasNext())
    		{
    			ClassA.Row row = rowIterator.next();
    			ClassB classB = conversionService.convert(row, ClassB.class);
    			//noinspection unchecked
    			target.add(classB);
    		}
    
    		return target;
    	}
    }
    Just to note I already have Converter to convert from ClassA.Row to ClassB, that was quite straightforward.
    Now I'm not sure if this implementation of ClassAToCollectionOfClassB makes any sense. I'm not sure if the getConvertibleTypes() and matches() methods are making sense. More importantly I still don't know how to create the target TypeDescriptor:

    Code:
        ClassA classA = ... // no problem here
        TypeDescriptor targetTypeDescriptor = ... // how to create this one if I want convert to List<ClassB>
        converterService.convert(classA, TypeDescriptor.forObject(classA), targetTypeDescriptor);
    Any help appreciated.
Working...
X