I'm using the Spring GenericConversionService.
The convert method in question has the following signature:
public <T> T convert(Object source, Class<T> targetType)
List<B>.class
is not valid Java syntax.
This worked for me:
List<A> sourceList = ...;
conversionService.convert(sourceList, (Class<List<B>>)(Class<?>)List.class);
Got the idea from here:
StackOverflow - Class object of generic class
Edit:
The above did not truly work. No compile errors, however it resulted in the sourceList not being converted, and being assigned to the targetList. This resulted in various exceptions downstream while attempting to use the targetList.
My current solution is to extend Spring's GenericConversionService and add my own convert method to handle lists.
Here's the convert method:
@SuppressWarnings({"rawtypes", "unchecked"})
public <T> List<T> convert(List<?> sourceList, Class<T> targetClass) {
Assert.notNull(sourceList, "Cannot convert null list.");
List<Object> targetList = new ArrayList();
for (int i = 0; i < sourceList.size(); i++) {
Object o = super.convert(sourceList.get(i), targetClass);
targetList.add(o);
}
return (List<T>) targetList;
}
And it can be called like the following:
List<A> sourceList = ...;
List<B> targetList = conversionService.convert(sourceList, B.class);
Love to see if anyone has a better way to handle this common scenario.
, List>`.
Off course this does not work because of type erasure. But the problem is not the code but the fact
Spring applies the convertor for all Lists at runtime, even for ones that do not contain Strings or Roles.
– JohnDoDo Oct 12 '11 at 10:20x y
` – JohnDoDo Oct 13 '11 at 07:51