实体类的copy
时间: 2023-10-01 15:09:52 浏览: 36
实体类的copy操作可以通过多种方式实现,以下是其中几种常见的方式:
1. 使用基本数据类型和String的copy构造函数或者clone方法进行复制。
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 使用copy构造函数进行复制
public Person(Person person) {
this.name = person.name;
this.age = person.age;
}
// 使用clone方法进行复制
@Override
public Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
}
```
2. 使用序列化和反序列化进行复制。
```java
public class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 使用序列化和反序列化进行复制
public Person copy() throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
oos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (Person) ois.readObject();
}
}
```
3. 使用BeanUtils或者PropertyUtils进行复制。
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 使用BeanUtils进行复制
public Person copy() throws IllegalAccessException, InvocationTargetException {
Person person = new Person("", 0);
BeanUtils.copyProperties(person, this);
return person;
}
// 使用PropertyUtils进行复制
public Person copy() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Person person = new Person("", 0);
PropertyUtils.copyProperties(person, this);
return person;
}
}
```
需要注意的是,以上几种方式都是浅拷贝,如果需要实现深拷贝,需要对引用类型的成员变量进行处理。