对象序列化与反序列化

可以用来做深度拷贝

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * Created by lzd on 2016年6月23日 下午3:20:32  
 */
public class Demo1 {
    
    public static void main(String[] args) throws Exception{
        
        User user = new User();
        user.setId(123);
        user.setName("123456");
        
        byte[] serializdObject = Demo1.serializdObject(user);
        
        User uu = Demo1.unSerializedObject(serializdObject);
        
        System.out.println(uu);
        
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T unSerializedObject(byte[] bt){
        T t = null;
        try (ByteArrayInputStream byteIn = new ByteArrayInputStream(bt);
                ObjectInputStream objIn = new ObjectInputStream(byteIn)){
            t = (T) objIn.readObject();
        } catch (Exception e) {
            
        }
        return t;
    }
    
    public static byte[] serializdObject(Object obj){
        byte[] bt = null;
        try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                ObjectOutputStream objOut = new ObjectOutputStream(byteOut)){
                objOut.writeObject(obj);
                bt = byteOut.toByteArray();
        } catch (IOException e) {
            
        }
        return bt;
    }
    
}

class User implements Serializable{

    private static final long serialVersionUID = 1L;
    
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", " + (name != null ? "name=" + name : "")
                + "]";
    }
}
posted @ 2016-06-23 16:29  姩澕  阅读(133)  评论(0编辑  收藏  举报