package org.springblade.flow.base.util;

import java.io.*;

/**
 * @author LoveMyOrange
 * @create 2022-02-02 17:02
 */
public class ObjectUtils {

    public static  byte[] toByteArray(Object object){
        byte[] bytes =null;
        ByteArrayOutputStream bos=null;
        ObjectOutputStream oos=null;
        try{
            bos=new ByteArrayOutputStream();
            oos=new ObjectOutputStream(bos);
            oos.writeObject(object);
            oos.flush();
            bytes=bos.toByteArray();
        }catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(oos!=null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(bos!=null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytes;
    }

    public static Object toObject(byte[] bytes){
        Object object=null;
        ByteArrayInputStream bis=null;
        ObjectInputStream ois=null;
        try{
            bis=new ByteArrayInputStream(bytes);
            ois=new ObjectInputStream(bis);
            object=ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            if(ois!=null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return object;
    }

}
