ModelMapper字段映射

时间:2018-06-21 16:03:08

标签: java modelmapper

我对ModelMapper框架有麻烦。请说明为什么我会看到以下行为。

我在build.gradle中有以下依赖项

compile group: 'org.modelmapper', name: 'modelmapper', version: '2.0.0'

和某类客户:

public class Customer {

    private String name;
    private int age;

    public Customer() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("name", name)
                .add("age", age)
                .toString();
    }
}

我还有一个映射器:

public class CustomerPropertyMap extends PropertyMap<Customer, Customer> {

    private final Condition<String, String> isFred = s -> isFred(s.getSource());

    @Override
    protected void configure() {
        when(isFred).map(source.getName()).setName("George");
        map(source.getAge(), destination.getAge());
    }

    boolean isFred(String s) {
        return "Fred".equals(s);
    }
}

和测试

public class PropertyMapTest {
    CustomerPropertyMap customerPropertyMap = new CustomerPropertyMap();
    ModelMapper modelMapper = new ModelMapper();

    @Before
    public void init() {
        modelMapper.addMappings(customerPropertyMap);
    }

    @Test
    public void fred() {
        Customer customer = new Customer();
        customer.setAge(40);
        customer.setName("Fred");
        Customer mapped = modelMapper.map(customer, Customer.class);
        System.out.println(mapped);
    }

    @Test
    public void nonFred() {
        Customer customer = new Customer();
        customer.setAge(40);
        customer.setName("Qwerty");
        Customer mapped = modelMapper.map(customer, Customer.class);
        System.out.println(mapped);
    }
}
在fred()方法中,

在nonFred(“ Customer {name = null,age = 40}”)中输出为“ Customer {name = Fred,age = 40}”。你能解释一下为什么吗?为什么在第一种方法中看不到输出“ George”?

1 个答案:

答案 0 :(得分:1)

何时用于源类型和目标类型之间的条件映射

在您的情况下,仅当满足条件“ Fred”时才映射名称。equals(name)