List序列化及反序列化

2018-04-28  本文已影响571人  未名枯草

代码举例:


/**
*  序列化接口-使用泛型
*/
public interface SerializeObject <T>{

   /**
    * 序列化
    * @param t
    * @return
    */

    byte[]serialize(List<T> t);

    /**
    * 反序列化
    * @param bytes
    * @return
    */
    List<T> unSerialize(byte[] bytes);
}


/**
*  List序列化实现类
*/
public class SerializeObjectImp<T>  limplements SerializeObject<T> {

    private Class<T> type;

    public SerializeObjectImpl(Class<T> type) {
          this.type = type;

    }

    public T[] create(Class<T> type,int size) {
       return (T[]) Array.newInstance(type, size);
    }

    @Override
    public byte[]serialize(List<T> t) {

        byte[] bytes =null;
        ByteArrayOutputStream bos =new ByteArrayOutputStream();

        try {

            ObjectOutputStream out =new ObjectOutputStream(bos);

            //将List转换成数组
            T[] obj = create(type,t.size());

            t.toArray(obj);

            //执行序列化存储
            out.writeObject(obj);

            out.flush();

            bytes = bos.toByteArray ();

            out.close();
            bos.close();

        }catch (IOException e) {
            e.printStackTrace();
        }
       return bytes;
    }

    @Override
    public List<T> unSerialize(byte[] bytes) {

        ObjectInputStream ois =null;

        List<T> list =null;

        try {

            ByteArrayInputStream bis =new ByteArrayInputStream (bytes);

            ois =new ObjectInputStream(bis);

            T[] obj = (T[])ois.readObject();

            //将数组转换成List
            list = Arrays.asList(obj);

            ois.close();

        }catch (IOException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
            return list;
    }
}

对象T,必须implements Serializable,才能序列化;

上一篇 下一篇

猜你喜欢

热点阅读