打字猴:1.70044199e+09
1700441990
1700441991 //拷贝一个对象
1700441992
1700441993 @SuppressWarnings(“unchecked”)
1700441994
1700441995 public static<T extends Serializable>T clone(T obj){
1700441996
1700441997 //拷贝产生的对象
1700441998
1700441999 T clonedObj=null;
1700442000
1700442001 try{
1700442002
1700442003 //读取对象字节数据
1700442004
1700442005 ByteArrayOutputStream baos=new ByteArrayOutputStream();
1700442006
1700442007 ObjectOutputStream oos=new ObjectOutputStream(baos);
1700442008
1700442009 oos.writeObject(obj);
1700442010
1700442011 oos.close();
1700442012
1700442013 //分配内存空间,写入原始对象,生成新对象
1700442014
1700442015 ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
1700442016
1700442017 ObjectInputStream ois=new ObjectInputStream(bais);
1700442018
1700442019 //返回新对象,并做类型转换
1700442020
1700442021 clonedObj=(T)ois.readObject();
1700442022
1700442023 ois.close();
1700442024
1700442025 }catch(Exception e){
1700442026
1700442027 e.printStackTrace();
1700442028
1700442029 }
1700442030
1700442031 return clonedObj;
1700442032
1700442033 }
1700442034
1700442035 }
1700442036
1700442037 此工具类要求被拷贝的对象必须实现Serializable接口,否则是没办法拷贝的(当然,使用反射那是另外一种技巧),上一个建议中的例子只要稍微修改一下即可实现深拷贝,代码如下:
1700442038
1700442039 class Person implements Serializable{
[ 上一页 ]  [ :1.70044199e+09 ]  [ 下一页 ]