实现序列化接口Serializable也可以控制对变量和transient变量的序列化控制,请看代码
package com.bird.thinking; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * @use 实现Serializable接口的可控制序列化实现 * @author Bird * */ public class SerialCtl implements Serializable { private static final long serialVersionUID = 1L; private String a; private transient String b;//注意其为transient public SerialCtl(String aa, String bb){ a = "Not Transient : " + aa; b = "Transient :" + bb; } public String toString(){ return a + "\n" + b; } private void writeObject(ObjectOutputStream stream) throws Exception{ stream.defaultWriteObject();//调用原来的方法写入非transient变量 stream.writeObject(b);//自己写方法序列化transient变量 } private void readObject(ObjectInputStream stream) throws Exception{ stream.defaultReadObject();//默认读取非transient变量 b = (String) stream.readObject(); } public static void main(String[] args) throws Exception{ SerialCtl sc = new SerialCtl("test1", "Test2"); System.out.println("Before:\n" + sc); ByteArrayOutputStream buf = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(buf); o.writeObject(sc); Thread.sleep(500); //现在要反序列化了哦 ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf.toByteArray())); SerialCtl sc2 = (SerialCtl) in.readObject(); System.out.println("After:\n" + sc2); } }
运行结果为Before: Not Transient : test1 Transient :Test2 After: Not Transient : test1 Transient :Test2 可以发现,transient变量照样被序列化和反序列化了