子非鱼

BlogJava 首页 新随笔 联系 聚合 管理
  21 Posts :: 0 Stories :: 1 Comments :: 0 Trackbacks
 1/**
 2 * 部分类的copy方法实现
 3 *
 4 */

 5public class CopyFactoryImpl implements CopyFactory{
 6
 7    public Object copy(Object from){
 8        if(from != null){
 9//            if(from instanceof Params)
10//                return copyParams((Params)from);
11//            if(from instanceof Value)
12//                return copyValue((Value)from);
13//            if(from instanceof OvertimePolicies)
14//                return copyPolicies((OvertimePolicies)from);
15//            if(from instanceof Event)
16//                return copyEvent((Event)from);
17            
18            return copyObject(from);//from应Serialization
19            
20        }

21        
22        return null;
23    }

24    
25
26    /**
27     * 缓存复制方式拷贝
28     * @param from
29     * @return
30     */

31    public Object copyObject(Object from){
32       try{
33          // 在内存中开辟一块缓冲区,用于将源对象写入
34          ByteArrayOutputStream bout = new ByteArrayOutputStream();
35          ObjectOutputStream out = new ObjectOutputStream(bout);
36          //通过Serialization机制将自身写入该缓冲区
37          out.writeObject(from);
38          out.close();
39
40          // 找到刚才开辟的缓冲区准备读取
41          ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
42          ObjectInputStream in = new ObjectInputStream(bin);
43          //将刚才写入的内容读入目标对象
44          Object target = in.readObject();
45          in.close();
46
47          //返回目标对象,拷贝完毕
48          return target;
49       }
catch (Exception e){
50          return null;
51       }

52    }

53}
posted on 2007-07-25 16:51 子非鱼 阅读(240) 评论(0)  编辑  收藏 所属分类: JAVA