transient 短暂的,临时的
java中一个对象只要实现了Serializable接口,这个对象就可以被序列化。但是如果你想要在序列化过程中规避掉某个成员变量,只要在该变量前添加关键字transient就行(对静态变量无效)
测试代码如下:
public class TransientTest { public static void main(String[] args) throws IOException, ClassNotFoundException { A a = new A(2, "a"); System.out.println(a); try { FileOutputStream fos = new FileOutputStream("d://mm.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(a); FileInputStream fis = new FileInputStream("d://mm.txt"); ObjectInputStream ois = new ObjectInputStream(fis); A newA = (A) ois.readObject(); System.out.println(newA); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class A implements Serializable { transient static int num = 5; int a; transient String b; public A(int a,String b) { this.a = a; this.b = b; } @Override public String toString() { return "a = " + a +"; b = " + b +"; num = " + num; } }
运行后控制台打印:
a = 2; b = a; num = 5
a = 2; b = null; num = 5