How to map collections in Dozer

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

I\'d like to do something like:

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


        
8条回答
  •  Happy的楠姐
    2020-12-14 17:29

    For that use case I once wrote a little helper class:

    import java.util.Collection;
    
    /**
     * Helper class for wrapping top level collections in dozer mappings.
     * 
     * @author Michael Ebert
     * @param 
     */
    public final class TopLevelCollectionWrapper {
    
        private final Collection collection;
    
        /**
         * Private constructor. Create new instances via {@link #of(Collection)}.
         * 
         * @see {@link #of(Collection)}
         * @param collection
         */
        private TopLevelCollectionWrapper(final Collection collection) {
            this.collection = collection;
        }
    
        /**
         * @return the wrapped collection
         */
        public Collection getCollection() {
            return collection;
        }
    
        /**
         * Create new instance of {@link TopLevelCollectionWrapper}.
         * 
         * @param 
         *            Generic type of {@link Collection} element.
         * @param collection
         *            {@link Collection}
         * @return {@link TopLevelCollectionWrapper}
         */
        public static  TopLevelCollectionWrapper of(final Collection collection) {
            return new TopLevelCollectionWrapper(collection);
        }
    }
    

    You then would call dozer in the following manner:

    private Mapper mapper;
    
    @SuppressWarnings("unchecked")
    public Collection getMappedCollection(final Collection collection) {
        TopLevelCollectionWrapper wrapper = mapper.map(
                TopLevelCollectionWrapper.of(collection),
                TopLevelCollectionWrapper.class);
    
        return wrapper.getCollection();
    }
    

    Only drawback: You get a "unchecked" warning on mapper.map(...) because of Dozers Mapper interface not handling generic types.

提交回复
热议问题