transient关键字

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)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1、transient关键字只能修饰变量,而不能修饰方法和类。2、被transient关键字修饰的变量不再能被序列...
    _fatef阅读 1,296评论 0 1
  • 1、transient的作用及使用方法 Java对象序列化是 JDK 1.1 中引入的一组开创性特性之一,用于作为...
    java部落阅读 1,503评论 0 0
  • 纯粹是个人学习总结,如有不对的地方请吐槽。 1. transient的作用及使用方法 我们都知道一个对象只要实现了...
    junwu_123阅读 322评论 0 0
  • 参考 stackoverflow - why-does-java-have-transient-fields 含义...
    xiaofudeng阅读 157评论 0 0
  • 喂,快跑! 为什么要跑? 老虎来了 为什么要跑? 那你等死吧! 喂,快跑! 为什么要跑? 狮子来了 为什么要跑? ...
    吹吧呃呃呃阅读 223评论 0 1

友情链接更多精彩内容