jdk序列化代码

@Slf4j
public class JdkSerializer implements Serializer{
    @Override
    public byte[] serialize(Object object) {
        if(object == null){
            return null;
        }
       try (
               //将流的定义写在这里会自动关流,不需要在写finally
               ByteArrayOutputStream baos = new ByteArrayOutputStream();
               ObjectOutputStream outputStream = new ObjectOutputStream(baos);
               ){
           outputStream.writeObject(object);
           return baos.toByteArray();
       }catch (IOException e){
           log.error("序列化对象盘【{}】时发生异常",object);
           throw new SerializeException(e);
       }


    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if(bytes == null || clazz == null){
            return null;
        }

        try (
                //将流的定义写在这里会自动关流,不需要在写finally
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                ObjectInputStream objectInputStream = new ObjectInputStream(bais);
        ){

            return (T) objectInputStream.readObject();
        }catch (IOException | ClassNotFoundException e){
            log.error("反序列化对象盘【{}】时发生异常",clazz);
            throw new SerializeException(e);
        }
        
    }
}

你可能感兴趣的:(java,开发语言)