How to map collections in Dozer

前端 未结 8 721
悲&欢浪女
悲&欢浪女 2020-12-14 17:25

I\'d like to do something like:

ArrayList objects = new ArrayList();
...
DozerBeanMapper MAPPER = new DozerBeanMapper         


        
相关标签:
8条回答
  • 2020-12-14 17:52

    What is happening is that you are getting bitten by type erasure. At runtime, java only sees an ArrayList.class. The type of CustomObject and NewObject aren't there, so Dozer is attempting to map a java.util.ArrayList, not your CustomObject to NewObject.

    What should work (totally untested):

    List<CustomObject> ori = new ArrayList<CustomObject>();
    List<NewObject> n = new ArrayList<NewObject>();
    for (CustomObject co : ori) {
        n.add(MAPPER.map(co, CustomObject.class));
    }
    
    0 讨论(0)
  • 2020-12-14 17:53

    I faced a similar issue, and decided on using a generic utility method to avoid iterating every time I needed to perform such mapping.

    public static <T, U> List<U> map(final Mapper mapper, final List<T> source, final Class<U> destType) {
    
        final List<U> dest = new ArrayList<>();
    
        for (T element : source) {
            dest.add(mapper.map(element, destType));
        }
    
        return dest;
    }
    

    Usage would then be something like:

        final List<CustomObject> accounts..... 
        final List<NewObject> actual = Util.map(mapper, accounts, NewObject.class);
    

    Possibly this could be simplified further though.

    0 讨论(0)
提交回复
热议问题