java如何拷贝一个对象
时间: 2023-07-20 17:43:59 浏览: 51
在 Java 中,拷贝一个对象可以使用以下两种方式:
1.浅拷贝:
使用 Object 类的 clone() 方法可以完成对象的浅拷贝,即只拷贝对象中的基本数据类型和对象的引用,并不会拷贝引用指向的对象。示例代码如下:
```
public class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
```
2.深拷贝:
如果需要拷贝对象中的引用类型对象,可以使用序列化和反序列化的方式实现深拷贝。示例代码如下:
```
public static Object deepCopy(Object obj) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
```