transient关键字主要用于修饰不需要序列化的域(Field),官方文档解释如下:
在序列化一个Java对象时,则可以使用transient关键字来修饰这些不需要进行序列化的属性。如果有一个Point类的对象point,再对point对象进行序列化时只会序列化域x和y,rho和theta域都不会序列化。
以序列化为例,对Point类稍稍修改,然后序列化,示例如下:
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class PointSeriable { public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { PointSeriable ps = new PointSeriable(); Point point = new Point(1, 2, 3.0f, 4.0f); String filename = "point"; ps.saveObj(point, filename); Object obj = ps.readObj(filename); if(obj instanceof Point){ Point p = (Point)obj; System.out.println("x=" + p.x); System.out.println("y=" + p.y); System.out.println("rho=" + p.rho); System.out.println("theta=" + p.theta); } } /** * 序列化对象obj * @param obj 要序列化的对象 * @param filename 序列化存储的文件名 * @throws FileNotFoundException * @throws IOException */ public void saveObj(Object obj, String filename) throws FileNotFoundException, IOException { ObjectOutputStream objos = new ObjectOutputStream(new FileOutputStream(new File(filename))); objos.writeObject(obj); objos.close(); } /** * 反序列化 * @param filename * @return * @throws FileNotFoundException * @throws IOException * @throws ClassNotFoundException */ public Object readObj(String filename) throws FileNotFoundException, IOException, ClassNotFoundException { ObjectInputStream objins = new ObjectInputStream(new FileInputStream(new File(filename))); Object obj = objins.readObject(); objins.close(); return obj; } } class Point implements Serializable{ private static final long serialVersionUID = 3583552501581482189L; int x, y; transient float rho, theta; Point() {} Point(int x, int y, float rho, float theta) { this.x = x; this.y = y; this.rho = rho; this.theta = theta; } }
x=1 y=2 rho=0.0 theta=0.0