gpt4 book ai didi

java - ModelMapper 字段映射

转载 作者:行者123 更新时间:2023-11-30 06:07:35 27 4
gpt4 key购买 nike

我在使用 ModelMapper 框架时遇到了麻烦。请解释为什么我看到以下行为。

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

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

还有一个类 Customer:

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”?

最佳答案

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

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

关于java - ModelMapper 字段映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50972990/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com