2009-12-18 19 views

回答

3

編輯:我已經更新了我的答案在外地一級,而不是在類級別使用自定義轉換器。

可能有其他的解決方案,但一種方法可以使用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()); 
} 
+0

感謝您的回答。但通過在課堂級別使用自定義轉換器,我不會從其他領域的推土機自動轉換中受益(我的真實'源'和'目的地'更豐富)。儘管如此使用例如我實現了「CollectionSizeConverter」這可能在現場級指定: <映射類型=「單向」> .... <字段定製轉換器=「my.CollectionSizeConverter」> 圖像 numOfImages 2009-12-19 07:19:29

+0

確實,在您的情況下使用字段轉換器可能會更好。但是,好吧,我想你明白了:) – 2009-12-19 14:34:49

0

這是一個有ModelMapper解決這個辦法:

ModelMapper modelMapper = new ModelMapper(); 
modelMapper.createTypeMap(Source.class, Destination.class).setConverter(
    new AbstractConverter<Source, Destination>() { 
     protected Destination convert(Source source) { 
     Destination dest = new Destination(); 
     dest.numOfImages = source.images.size(); 
     return dest; 
     } 
    }); 

本例使用Converter作爲Source和Destination類。

更多示例和文檔可在http://modelmapper.org