Dozer mapping generic types
Asked Answered
K

0

6

I want to map a data object to basically the same transport object using dozer. The objects contain a generic field. I expect the generic field to be mapped to the same type, in this example to be Integer. But the mapped object generic type is String. I am using dozer version 6.0.0. How can i map generics and keep the type?

Data Object:

public class DataObject<T> {
    T generic;

    public DataObject() {
    }

    public T getGeneric() {
        return generic;
    }

    public void setGeneric(final T generic) {
        this.generic = generic;
    }
}

Transport Object:

public class TransportObject<T> {
    T generic;

    public TransportObject() {
    }

    public T getGeneric() {
        return generic;
    }

    public void setGeneric(final T generic) {
        this.generic = generic;
    }
}

Mapping Test:

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
        */
    }
}
Kruller answered 18/7, 2017 at 10:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.