Merge pull request #2698 from top-zhang/v5-dev

fix: 修复 BeanUtil#copyProperties 源对象与目标对象都是 Map 时设置忽略属性无效问题
This commit is contained in:
Golden Looly 2022-11-08 20:04:32 +08:00 committed by GitHub
commit 4fdc443a4e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 58 additions and 0 deletions

View File

@ -12,6 +12,8 @@ import cn.hutool.core.util.ReflectUtil;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
@ -69,6 +71,11 @@ public class CopyOptions implements Serializable {
*/
protected boolean override = true;
/**
* 源对象和目标对象都是 {@code Map} , 需要忽略的源对象 {@code Map} key
*/
private Set<Object> ignoreKeySet;
/**
* 自定义类型转换器默认使用全局万能转换器转换
*/
@ -181,6 +188,7 @@ public class CopyOptions implements Serializable {
* @return CopyOptions
*/
public CopyOptions setIgnoreProperties(String... ignoreProperties) {
this.setIgnoreKeySet(ignoreProperties);
return setPropertiesFilter((field, o) -> false == ArrayUtil.contains(ignoreProperties, field.getName()));
}
@ -220,6 +228,16 @@ public class CopyOptions implements Serializable {
return setIgnoreError(true);
}
/**
* 设置忽略源 {@link Map} key set
* @param ignoreProperties 忽略的key
* @return CopyOptions
*/
public CopyOptions setIgnoreKeySet(String... ignoreProperties) {
this.ignoreKeySet = new HashSet<>(Arrays.asList(ignoreProperties));
return this;
}
/**
* 设置是否忽略字段的大小写
*
@ -363,4 +381,14 @@ public class CopyOptions implements Serializable {
protected boolean testPropertyFilter(Field field, Object value) {
return null == this.propertiesFilter || this.propertiesFilter.test(field, value);
}
/**
* 测试是否保留key, {@code true} 不保留 {@code false} 保留
*
* @param key {@link Map} key
* @return 是否保留
*/
protected boolean testMapKeyFilter(Object key) {
return this.ignoreKeySet.contains(key);
}
}

View File

@ -54,6 +54,12 @@ public class MapToMapCopier extends AbsCopier<Map, Map> {
return;
}
// 忽略不需要拷贝的 key,
if (true == copyOptions.testMapKeyFilter(sKey)) {
return;
}
// 获取目标值真实类型并转换源值
final Type[] typeArguments = TypeUtil.getTypeArguments(this.targetType);
if (null != typeArguments) {

View File

@ -0,0 +1,24 @@
package cn.hutool.core.bean;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* https://github.com/dromara/hutool/issues/2697
*/
public class Issue2697Test {
@Test
public void mapToMapTest(){
Map<String, String> mapA = new HashMap<>(16);
mapA.put("12", "21");
mapA.put("121", "21");
mapA.put("122", "21");
Map<String, String> mapB = new HashMap<>(16);
BeanUtil.copyProperties(mapA, mapB, "12");
System.out.println(mapB);
}
}