Clone Object by serializing
2014-06-20 12:32
302 查看
public class CloneUtils{
// 拷贝一个对象
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T obj) {
// 拷贝产生的对象
T clonedObj = null;
try {
// 读取对象字节数据
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
// 分配内存空间,写入原始对象,生成新对象
ByteArrayInputStream bais = new ByteArrayInputStream(baos
.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
// 返回新对象,并做类型转换
clonedObj = (T) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
return clonedObj;
}
}
Refer to http://blog.csdn.net/ncepuzhuang/article/details/9052077 原型模式
// 拷贝一个对象
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T obj) {
// 拷贝产生的对象
T clonedObj = null;
try {
// 读取对象字节数据
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
// 分配内存空间,写入原始对象,生成新对象
ByteArrayInputStream bais = new ByteArrayInputStream(baos
.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
// 返回新对象,并做类型转换
clonedObj = (T) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
return clonedObj;
}
}
Refer to http://blog.csdn.net/ncepuzhuang/article/details/9052077 原型模式
相关文章推荐
- Deep clone object by serialization
- PHP中对象的clone和引用的区别(Object Cloning and Passing by Reference in PHP)
- C# Object.MemberwiseClone 方法
- Java mail包出现"MimeMessage contains object of type javax.mail.util.SharedByteArrayInputStream instead of MimeMultipart"错误的修正办法
- Incorrect decrement of the reference count of an object that is not owned at this point by the caller1
- 为什么调用Object的clone方法却可以使得自己类中的对象被clone呢?
- [置顶] 顿悟JAVA,自己实现Object的Clone的约束关系(上)
- C# Parameter: Pass object by value, The copy constructor
- xjc-beyond sliding windows-Object Localization by Efficient Subwindow Search 论文的算法和知识点
- 图像修复二:基于 Object Removal by Exemplar-Based Inpainting 的改进算法
- 解决hibernate 删除异常: deleted object would be re-saved by cascade (remove deleted object from associations)
- spring整合jbpm Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(Z)V
- C# Object Clone
- Determine SQL Server memory use by database and object
- Dissecting the Windows Kernel - 关于ObReferenceObjectByHandle中对句柄的处理
- Object类中clone()方法的修饰符为什么是protected
- Tomcat报错:DBCP object created 2012-03-03 09:09:34 by the following code was never close
- java.lang.Object.clone()
- 解决hibernate 删除异常:deleted object would be re-saved by cascade
- Object对象clone方法总结+原型模式(笔记)