mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
!590 [新特性] CopyOptions支持以Lambda方式设置忽略属性列表
Merge pull request !590 from celee/v5-dev
This commit is contained in:
commit
04612516d4
@ -1,13 +1,19 @@
|
||||
package cn.hutool.core.bean.copier;
|
||||
|
||||
import cn.hutool.core.lang.Editor;
|
||||
import cn.hutool.core.lang.func.Func1;
|
||||
import cn.hutool.core.lang.func.LambdaUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 属性拷贝选项<br>
|
||||
@ -158,6 +164,33 @@ public class CopyOptions implements Serializable {
|
||||
return setPropertiesFilter((field, o) -> false == ArrayUtil.contains(ignoreProperties, field.getName()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置忽略的目标对象中属性列表,设置一个属性列表,不拷贝这些属性值,Lambda方式
|
||||
*
|
||||
* @param func1 忽略的目标对象中属性列表,设置一个属性列表,不拷贝这些属性值
|
||||
* @return CopyOptions
|
||||
*/
|
||||
public <P, R> CopyOptions setIgnoreProperties(Func1<P, R>... func1) {
|
||||
List<String> ignoreProperties = Arrays.asList(func1)
|
||||
.stream()
|
||||
.map(t -> {
|
||||
String name = LambdaUtil.getMethodName(t);
|
||||
if (name.startsWith("is")) {
|
||||
name = name.substring(2);
|
||||
} else if (name.startsWith("get") || name.startsWith("set")) {
|
||||
name = name.substring(3);
|
||||
} else {
|
||||
throw new RuntimeException("Error parsing property name '" + name + "'. Didn't start with 'is', 'get' or 'set'.");
|
||||
}
|
||||
if (name.length() == 1 || (name.length() > 1 && !Character.isUpperCase(name.charAt(1)))) {
|
||||
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
|
||||
}
|
||||
return name;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
return setPropertiesFilter((field, o) -> false == ignoreProperties.contains(field.getName()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否忽略字段的注入错误
|
||||
*
|
||||
|
@ -562,6 +562,22 @@ public class BeanUtilTest {
|
||||
Assert.assertNull(newFood.getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void copyBeanPropertiesFunctionFilterTest() {
|
||||
Person o = new Person();
|
||||
o.setName("asd");
|
||||
o.setAge(123);
|
||||
o.setOpenid("asd");
|
||||
|
||||
CopyOptions copyOptions = CopyOptions.create().setIgnoreProperties(Person::getAge,Person::getOpenid);
|
||||
Person n = new Person();
|
||||
BeanUtil.copyProperties(o, n, copyOptions);
|
||||
|
||||
// 是否忽略拷贝属性
|
||||
Assert.assertNotEquals(o.getAge(),n.getAge());
|
||||
Assert.assertNotEquals(o.getOpenid(),n.getOpenid());
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Food {
|
||||
@Alias("bookId")
|
||||
|
Loading…
x
Reference in New Issue
Block a user