我想使用dozer将数据对象映射到基本相同的传输对象。对象包含通用字段。我希望通用字段映射到相同的类型,在本例中为Integer。但映射的对象泛型类型是String。我使用的是dozer 6.0.0版。我如何绘制泛型并保持类型?
数据对象:
public class DataObject<T> {
T generic;
public DataObject() {
}
public T getGeneric() {
return generic;
}
public void setGeneric(final T generic) {
this.generic = generic;
}
}
运输对象:
public class TransportObject<T> {
T generic;
public TransportObject() {
}
public T getGeneric() {
return generic;
}
public void setGeneric(final T generic) {
this.generic = generic;
}
}
映射测试:
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
public class DozerGenericsTest {
@Test
public void should_map_generics() throws Exception {
//given
Mapper mapper = new DozerBeanMapper();
DataObject<Integer> dataObject1 = new DataObject<>();
dataObject1.setGeneric(42);
//when
TransportObject transportObject = mapper.map(dataObject1, TransportObject.class);
//then
Assert.assertThat(transportObject.getGeneric(), instanceOf(Integer.class));
/*
java.lang.AssertionError:
Expected: an instance of java.lang.Integer
but: "42" is a java.lang.String
*/
}
@Test
public void should_map_generics_by_object_instance() throws Exception {
//given
Mapper mapper = new DozerBeanMapper();
DataObject<Integer> dataObject1 = new DataObject<>();
dataObject1.setGeneric(42);
//when
TransportObject<Integer> transportObject = new TransportObject<>();
mapper.map(dataObject1, transportObject);
//then
Assert.assertThat(transportObject.getGeneric(), instanceOf(Integer.class));
/*
java.lang.AssertionError:
Expected: an instance of java.lang.Integer
but: "42" is a java.lang.String
*/
}
}