您的位置:首页 > 移动开发 > Objective-C

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 原型模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐