深层克隆的实现

深克隆的最简单方法:

 

public Object deepCopy(Object src) throws IOException, ClassNotFoundException{    
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();    
        ObjectOutputStream out = new ObjectOutputStream(byteOut);    
        out.writeObject(src);    
        
        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());    
        ObjectInputStream in =new ObjectInputStream(byteIn);    
        Object dest = (Object)in.readObject();    
        return dest;    
    }  

 方便又实用,哈哈。

今天有一个需要,将DO放入Memcache,需要计算每个DO的大小,也可以用类似方法实现(单位:KB)。

    public static double getLength(Object src) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(src);
        return (double) (new ByteArrayInputStream(byteOut.toByteArray()).available()) / 1024;

    }

你可能感兴趣的:(克隆)