代码生成(复制一个JavaBean)
时间: 2024-01-12 10:02:37 浏览: 72
java bean代码生成器
4星 · 用户满意度95%
以下是使用序列化和反序列化技术复制一个JavaBean的示例代码:
```java
import java.io.*;
public class JavaBeanUtils {
public static <T extends Serializable> T copy(T object) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
oos.close();
bos.close();
byte[] byteData = bos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
T copy = (T) new ObjectInputStream(bais).readObject();
return copy;
}
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
User user1 = new User("John", 20);
User user2 = JavaBeanUtils.copy(user1);
System.out.println(user1);
System.out.println(user2);
}
}
class User implements Serializable {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
输出结果:
```
User{name='John', age=20}
User{name='John', age=20}
```
可以看到,使用JavaBeanUtils.copy()方法即可复制一个JavaBean对象。
阅读全文