java如何拷贝类
拷贝类的方法
在Java中拷贝类对象通常涉及浅拷贝和深拷贝两种方式,具体实现取决于需求。以下是几种常见的实现方法:
实现Cloneable接口并重写clone方法
Java中的Cloneable是一个标记接口,用于指示类可以进行克隆操作。通过重写Object类的clone方法实现浅拷贝。
class MyClass implements Cloneable {
private int value;
private String name;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
调用方式:
MyClass original = new MyClass();
MyClass copy = (MyClass) original.clone();
使用拷贝构造函数
通过定义一个接受同类对象作为参数的构造函数来实现拷贝。
class MyClass {
private int value;
private String name;
public MyClass(MyClass other) {
this.value = other.value;
this.name = other.name;
}
}
调用方式:
MyClass original = new MyClass();
MyClass copy = new MyClass(original);
使用Apache Commons或Spring BeanUtils进行属性拷贝
第三方库如Apache Commons BeanUtils或Spring BeanUtils提供了便捷的属性拷贝方法。
import org.apache.commons.beanutils.BeanUtils;
MyClass original = new MyClass();
MyClass copy = new MyClass();
BeanUtils.copyProperties(copy, original);
使用序列化实现深拷贝
通过序列化和反序列化实现完全的深拷贝,适用于复杂对象图。
import java.io.*;
class MyClass implements Serializable {
private int value;
private String name;
public MyClass deepCopy() throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (MyClass) ois.readObject();
}
}
调用方式:
MyClass original = new MyClass();
MyClass copy = original.deepCopy();
使用MapStruct等映射工具
对于复杂对象的拷贝,可以使用MapStruct等代码生成工具,自动生成映射代码。
@Mapper
public interface MyClassMapper {
MyClassMapper INSTANCE = Mappers.getMapper(MyClassMapper.class);
MyClass copy(MyClass original);
}
调用方式:

MyClass original = new MyClass();
MyClass copy = MyClassMapper.INSTANCE.copy(original);
注意事项
- 浅拷贝仅复制对象的字段值,对于引用类型字段,复制的是引用而非对象本身。
- 深拷贝会递归复制所有引用对象,确保完全独立。
- 使用
Cloneable接口时需注意clone方法是protected的,外部调用可能需要通过公共方法暴露。 - 序列化方式要求所有相关类实现
Serializable接口。






