
前言
SerializationUtils是spring基于java原生的序列化与反序列化机制实现的工具类,方便程序猿快速开发。
代码片段
package org.springframework.util;
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;
public abstract class {
public static byte[] serialize(Object object) { if (object == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(object); oos.flush(); } catch (IOException ex) { throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex); } return baos.toByteArray(); }
public static Object deserialize(byte[] bytes) { if (bytes == null) { return null; } try { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); return ois.readObject(); } catch (IOException ex) { throw new IllegalArgumentException("Failed to deserialize object", ex); } catch (ClassNotFoundException ex) { throw new IllegalStateException("Failed to deserialize object type", ex); } }
}
|
近期评论