- 当一个对象的实例变量引用其他对象,序列化该对象时也把引用对象进行序列化;
- 当一个父类实现序列化,子类自动实现序列化,不需要显式实现Serializable接口;
- static,transient后的变量不能被序列化;
public abstract class ObjectUtils { public static byte[] serializeObject(Object o) throws IOException { if (o == null) { return null; } ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024); ObjectOutputStream objectStream = new ObjectOutputStream(byteStream); try { objectStream.writeObject(o); return byteStream.toByteArray(); } finally { byteStream.close(); objectStream.close(); } } public static Object unserializeObject(byte[] bytes) throws IOException, ClassNotFoundException { if (bytes == null) { return null; } ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); ObjectInputStream objectStream = new ObjectInputStream(byteStream); try { return objectStream.readObject(); } finally { byteStream.close(); objectStream.close(); } } }
克隆对象:
public static <T> T clone(T obj) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bout); oos.writeObject(obj); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bin); return (T) ois.readObject(); // 说明:调用ByteArrayInputStream或ByteArrayOutputStream对象的close方法没有任何意义 // 这两个基于内存的流只要垃圾回收器清理对象就能够释放资源,这一点不同于对外部资源(如文件流)的释放 }