1.描述
transient关键字只可以修饰全局变量, 不可以修饰本地变量、方法及类,被trasient关键字修饰的变量不可以被序列化
2.具体例子
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class TransientDomain implements Serializable {
private String keyOne;
private transient String keyTwo;
}
public static void main(String[] args) throws Exception {
TransientDomain transientDomain = new TransientDomain();
transientDomain.setKeyOne("valueOne");
transientDomain.setKeyTwo("valueTwo");
File targetFile = new File("temp3.txt");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(targetFile));
oos.writeObject(transientDomain);
oos.flush();
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(targetFile));
TransientDomain newTransientDomain = (TransientDomain) ois.readObject();
ois.close();
System.out.println(newTransientDomain);
}
输出结果:TransientDomain(keyOne=valueOne, keyTwo=null)
网友评论