有没有办法在推土机中映射集合大小?

class Source {
    Collection<String> images;
}

class Destination {
  int numOfImages;
}

最佳答案

编辑:我已经更新了答案,以便在字段级别而不是在类级别使用自定义转换器。

可能还有其他解决方案,但一种方法是使用Custom Converter。我已将getter和setter添加到您的类中,并编写了以下转换器:

package com.mycompany.samples.dozer;

import java.util.Collection;

import org.dozer.DozerConverter;

public class TestCustomFieldConverter extends
        DozerConverter<Collection, Integer> {

    public TestCustomFieldConverter() {
        super(Collection.class, Integer.class);
    }

    @Override
    public Integer convertTo(Collection source, Integer destination) {
        if (source != null) {
            return source.size();
        } else {
            return 0;
        }
    }

    @Override
    public Collection convertFrom(Integer source, Collection destination) {
        throw new IllegalStateException("Unknown value!");
    }
}


然后,在custom XML mapping file中声明它:

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://dozer.sourceforge.net
          http://dozer.sourceforge.net/schema/beanmapping.xsd">
  <mapping>
    <class-a>com.mycompany.samples.dozer.Source</class-a>
    <class-b>com.mycompany.samples.dozer.Destination</class-b>
    <field custom-converter="com.mycompany.samples.dozer.TestCustomFieldConverter">
      <a>images</a>
      <b>numOfImages</b>
    </field>
  </mapping>
</mappings>


使用此设置,以下测试成功通过:

@Test
public void testCollectionToIntMapping() {
    List<String> mappingFiles = new ArrayList<String>();
    mappingFiles.add("com/mycompany/samples/dozer/somedozermapping.xml");
    Mapper mapper = new DozerBeanMapper(mappingFiles);

    Source sourceObject = new Source();
    sourceObject.setImages(Arrays.asList( "a", "b", "C" ));

    Destination destObject = mapper.map(sourceObject, Destination.class);

    assertEquals(3, destObject.getNumOfImages());
}

关于java - 推土机中的 map 集合大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1931212/

10-12 00:12