有兩種方式:
1). 實現Cloneable接口並重寫Object類中的clone()方法;
2). 實現Serializable接口,經過對象的序列化和反序列化實現克隆,能夠實現真正的深度克隆,代碼以下。java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import
java.io.ByteArrayInputStream;
import
java.io.ByteArrayOutputStream;
import
java.io.ObjectInputStream;
import
java.io.ObjectOutputStream;
public
class
MyUtil {
private
MyUtil() {
throw
new
AssertionError();
}
public
static
<T> T clone(T obj)
throws
Exception {
ByteArrayOutputStream bout =
new
ByteArrayOutputStream();
ObjectOutputStream oos =
new
ObjectOutputStream(bout);
oos.writeObject(obj);
ByteArrayInputStream bin =
new
ByteArrayInputStream(bout.toByteArray());
ObjectInputStream ois =
new
ObjectInputStream(bin);
return
(T) ois.readObject();
// 說明:調用ByteArrayInputStream或ByteArrayOutputStream對象的close方法沒有任何意義
// 這兩個基於內存的流只要垃圾回收器清理對象就可以釋放資源,這一點不一樣於對外部資源(如文件流)的釋放
}
}
|
下面是測試代碼:ide
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
|
import
java.io.Serializable;
/**
* 人類
* @author
*
*/
class
Person
implements
Serializable {
private
static
final
long
serialVersionUID = -9102017020286042305L;
private
String name;
// 姓名
private
int
age;
// 年齡
private
Car car;
// 座駕
public
Person(String name,
int
age, Car car) {
this
.name = name;
this
.age = age;
this
.car = car;
}
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;
}
public
Car getCar() {
return
car;
}
public
void
setCar(Car car) {
this
.car = car;
}
@Override
public
String toString() {
return
"Person [name="
+ name +
", age="
+ age +
", car="
+ car +
"]"
;
}
}
|
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
|
/**
* 小汽車類
* @author
*
*/
class
Car
implements
Serializable {
private
static
final
long
serialVersionUID = -5713945027627603702L;
private
String brand;
// 品牌
private
int
maxSpeed;
// 最高時速
public
Car(String brand,
int
maxSpeed) {
this
.brand = brand;
this
.maxSpeed = maxSpeed;
}
public
String getBrand() {
return
brand;
}
public
void
setBrand(String brand) {
this
.brand = brand;
}
public
int
getMaxSpeed() {
return
maxSpeed;
}
public
void
setMaxSpeed(
int
maxSpeed) {
this
.maxSpeed = maxSpeed;
}
@Override
public
String toString() {
return
"Car [brand="
+ brand +
", maxSpeed="
+ maxSpeed +
"]"
;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class
CloneTest {
public
static
void
main(String[] args) {
try
{
Person p1 =
new
Person(
"Hao LUO"
,
33
,
new
Car(
"Benz"
,
300
));
Person p2 = MyUtil.clone(p1);
// 深度克隆
p2.getCar().setBrand(
"BYD"
);
// 修改克隆的Person對象p2關聯的汽車對象的品牌屬性
// 原來的Person對象p1關聯的汽車不會受到任何影響
// 由於在克隆Person對象時其關聯的汽車對象也被克隆了
System.out.println(p1);
}
catch
(Exception e) {
e.printStackTrace();
}
}
}
|