转瞬即逝的 是在中使用的变量修饰符 系列化 .在序列化时,如果我们不想在文件中保存特定变量的值,那么我们使用 转瞬即逝的 关键词。当JVM遇到 转瞬即逝的 关键字,则忽略变量的原始值,并保存该变量数据类型的默认值。
null
转瞬即逝的 关键字在满足安全约束方面起着重要作用。现实生活中有各种各样的例子,我们不想将私人数据保存在文件中。另一种用法 转瞬即逝的 关键字不是序列化变量,该变量的值可以使用其他序列化对象或系统(如人的年龄、当前日期等)计算/派生。 实际上,我们只序列化了那些表示实例状态的字段,毕竟序列化就是要将对象的状态保存到文件中。这是一个好习惯 转瞬即逝的 在序列化期间带有类的私有机密字段的关键字。
// A sample class that uses transient keyword to // skip their serialization. class Test implements Serializable { // Making password transient for security private transient String password; // Making age transient as age is auto- // computable from DOB and current date. transient int age; // serialize other fields private String username, email; Date dob; // other code } |
瞬态和静态: 自从 静止的 字段不是对象状态的一部分,使用字段没有任何用途/影响 转瞬即逝的 带有静态变量的关键字。但是没有编译错误。
暂时和最终: 最终变量由其值直接序列化,因此将最终变量声明为 转瞬即逝的 .但是没有编译时错误。
// Java program to demonstrate transient keyword // Filename Test.java import java.io.*; class Test implements Serializable { // Normal variables int i = 10 , j = 20 ; // Transient variables transient int k = 30 ; // Use of transient has no impact here transient static int l = 40 ; transient final int m = 50 ; public static void main(String[] args) throws Exception { Test input = new Test(); // serialization FileOutputStream fos = new FileOutputStream( "abc.txt" ); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(input); // de-serialization FileInputStream fis = new FileInputStream( "abc.txt" ); ObjectInputStream ois = new ObjectInputStream(fis); Test output = (Test)ois.readObject(); System.out.println( "i = " + output.i); System.out.println( "j = " + output.j); System.out.println( "k = " + output.k); System.out.println( "l = " + output.l); System.out.println( "m = " + output.m); } } |
输出:
i = 10 j = 20 k = 0 l = 40 m = 50
本文由 高拉夫·米格拉尼 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END