forked from chenssy89/jutils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneUtils.java
More file actions
75 lines (68 loc) · 2 KB
/
CloneUtils.java
File metadata and controls
75 lines (68 loc) · 2 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
package com.JUtils.clone;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
/**
* 克隆工具类,进行深克隆,包括对象、集合
*
* @Author:chenssy
* @date:2014年8月9日
*/
public class CloneUtils {
/**
* 采用对象的序列化完成对象的深克隆
* @autor:chenssy
* @date:2014年8月9日
*
* @param obj
* 待克隆的对象
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends Serializable> T cloneObject(T obj) {
T cloneObj = null;
try {
// 写入字节流
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream obs = new ObjectOutputStream(out);
obs.writeObject(obj);
obs.close();
// 分配内存,写入原始对象,生成新对象
ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream ois = new ObjectInputStream(ios);
// 返回生成的新对象
cloneObj = (T) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
return cloneObj;
}
/**
* 利用序列化完成集合的深克隆
* @autor:chenssy
* @date:2014年8月9日
*
* @param collection
* 待克隆的集合
* @return
* @throws ClassNotFoundException
* @throws java.io.IOException
*/
@SuppressWarnings("unchecked")
public static <T> Collection<T> cloneCollection(Collection<T> collection) throws ClassNotFoundException, IOException{
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(collection);
out.close();
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
Collection<T> dest = (Collection<T>) in.readObject();
in.close();
return dest;
}
}