对象深克隆
1、编写一个工具类
public class StreamUtil <T> {
public static Object copyObject(Object object) throws Exception{
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(byteOut);
objOut.writeObject(object); // 将对象写入内存
ObjectInputStream objIn = new ObjectInputStream(
new ByteArrayInputStream(byteOut.toByteArray()));
Object objCloned = objIn.readObject(); // 读取内存中的对象
FileUtil.close(objOut,objIn); // 关闭资源
return objCloned;
}
}
2、关闭资源的方法
/**
* 关闭资源
*
* @param c 资源
*/
public static void close(Closeable... c){
for(Closeable clo : c){
FileUtil.close(clo);
}
}
/**
* 关闭资源
*
* @param clo 资源
*/
public static void close(Closeable clo){
try {
if(null != clo){
clo.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
clo = null;
}
}
3、定义实体类
注意:被序列化的实体类必须实现Serializable接口,且实体类的全局变量也必须实现Serializable接口
public class Student implements Serializable{
private static final long serialVersionUID = -6525202728552190615L;
private String name;
private int age;
private double score;
}
4、测试
public static void main(String[] args) {
//File sourceFile = new File("myFirstFile"+File.separator+"美女01.jpg");
//File targetFile = new File("myFirstFile"+File.separator+"美女03.jpg");
Student student = new Student("chengya",23,98.5);
Student stu = null ;
try {
stu = (Student)StreamUtil.copyObject(student);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(null == stu); // false
System.out.println(stu == student); // false
System.out.println(stu.equals(student)); // true
System.out.println("stu"+stu.toString());
System.out.println("student"+stu.toString());
}