DeepCopyUtils.java
2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.xly.util;
import java.util.*;
import java.util.function.Function;
public class DeepCopyUtils {
/**
* 通用Map深拷贝方法
* @param original 原始Map
* @param keyCopier key拷贝函数(对于不可变对象如String,可以直接返回原对象)
* @param valueCopier value拷贝函数
*/
public static <K, V> Map<K, V> deepCopyMap(
Map<K, V> original,
Function<K, K> keyCopier,
Function<V, V> valueCopier) {
if (original == null) return null;
Map<K, V> copy = new HashMap<>(original.size());
original.forEach((key, value) -> {
K copiedKey = keyCopier.apply(key);
V copiedValue = valueCopier.apply(value);
copy.put(copiedKey, copiedValue);
});
return copy;
}
/**
* 自动类型推断的深拷贝(简化版)
*/
@SuppressWarnings("unchecked")
public static <T> T deepCopy(T obj) {
if (obj == null) return null;
if (obj instanceof Map) {
Map<?, ?> map = (Map<?, ?>) obj;
Map<Object, Object> copy = new HashMap<>();
map.forEach((k, v) -> {
copy.put(deepCopy(k), deepCopy(v));
});
return (T) copy;
} else if (obj instanceof List) {
List<?> list = (List<?>) obj;
List<Object> copy = new ArrayList<>();
list.forEach(item -> copy.add(deepCopy(item)));
return (T) copy;
} else if (obj instanceof Set) {
Set<?> set = (Set<?>) obj;
Set<Object> copy = new HashSet<>();
set.forEach(item -> copy.add(deepCopy(item)));
return (T) copy;
} else if (obj.getClass().isArray()) {
// 数组处理
return cloneArray(obj);
} else {
// 基本类型、字符串、不可变对象等返回原对象
// 如果需要对象拷贝,可以在这里添加序列化或反射拷贝
return obj;
}
}
private static <T> T cloneArray(T array) {
Class<?> componentType = array.getClass().getComponentType();
if (componentType.isPrimitive()) {
// 基本类型数组
int length = java.lang.reflect.Array.getLength(array);
Object copy = java.lang.reflect.Array.newInstance(componentType, length);
System.arraycopy(array, 0, copy, 0, length);
@SuppressWarnings("unchecked")
T result = (T) copy;
return result;
} else {
// 对象数组
Object[] objArray = (Object[]) array;
Object[] copy = (Object[]) java.lang.reflect.Array.newInstance(
componentType, objArray.length);
for (int i = 0; i < objArray.length; i++) {
copy[i] = deepCopy(objArray[i]);
}
@SuppressWarnings("unchecked")
T result = (T) copy;
return result;
}
}
}