Hi all,
I'm trying to use the new Converter SPI to convert from ClassA to List<ClassB>. I have a following Converter:
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.Code:public class ClassAToListOfClassB implements Converter<ClassA, List<ClassB>> { public List<ClassB> convert(ClassA source) { List<ClassB> list = new ArrayList<ClassB>(); // convert return list; }
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:
Just to note I already have Converter to convert from ClassA.Row to ClassB, that was quite straightforward.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; } }
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:
Any help appreciated.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);


Reply With Quote
