package com.kmall.admin.cuspay.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; public class SerializeUtils { private static Logger logger = LoggerFactory.getLogger(SerializeUtils.class); public static Object deserialize(byte[] bytes) { return deserialize(bytes, Object.class); } /** * 反序列化 * @param bytes * @return */ public static T deserialize(byte[] bytes, Class... clazz) { Object result = null; if (isEmpty(bytes)) { return null; } try { ByteArrayInputStream byteStream = null; ObjectInputStream objectInputStream = null; try { try { byteStream = new ByteArrayInputStream(bytes); objectInputStream = new ObjectInputStream(byteStream); result = objectInputStream.readObject(); } catch (ClassNotFoundException ex) { throw new Exception("Failed to deserialize object type", ex); }finally { close(objectInputStream); close(byteStream); } } catch (Throwable ex) { throw new Exception("Failed to deserialize", ex); }finally { close(objectInputStream); close(byteStream); } } catch (Exception e) { logger.error("Failed to deserialize",e); } return (T)result; } public static boolean isEmpty(byte[] data) { return (data == null || data.length == 0); } public static byte[] serialize(Object object) { return serialize(object, Object.class); } /** * 序列化 * @param object * @return */ public static byte[] serialize(T object, Class clazz) { byte[] result = null; if (object == null) { return new byte[0]; } try { ByteArrayOutputStream byteStream = null; ObjectOutputStream objectOutputStream = null; try { if (!(object instanceof Serializable)) { throw new IllegalArgumentException(SerializeUtils.class.getSimpleName() + " requires a Serializable payload " + "but received an object of type [" + object.getClass().getName() + "]"); } byteStream = new ByteArrayOutputStream(128); objectOutputStream = new ObjectOutputStream(byteStream); objectOutputStream.writeObject(object); objectOutputStream.flush(); result = byteStream.toByteArray(); } catch (Throwable ex) { throw new Exception("Failed to serialize", ex); }finally { close(objectOutputStream); close(byteStream); } } catch (Exception ex) { logger.error("Failed to serialize",ex); } return result; } private static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { logger.error("close stream error"); e.printStackTrace(); } } } }