首页 / JAVA / 序列化Java中的最终瞬态如何工作
序列化Java中的最终瞬态如何工作
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了序列化Java中的最终瞬态如何工作,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2582字,纯文字阅读大概需要4分钟。
内容图文
![序列化Java中的最终瞬态如何工作](/upload/InfoBanner/zyjiaocheng/750/1240f69e64be4801b91fbe0a6d6a3741.jpg)
我正在阅读有关transient和final关键字的内容,我找到了一个答案,我们不能使用带有final关键字的transient关键字.我试过并感到困惑,因为这里工作正常.
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class SerExample{
public static void main(String... args){
Student foo = new Student(3,2,"ABC");
Student koo = new Student(6,4,"DEF");
try
{
FileOutputStream fos = new FileOutputStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(foo);
oos.writeObject(koo);
oos.close();
fos.close();
}
catch(Exception e){/**/}
try{
FileInputStream fis = new FileInputStream("abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println(ois.readObject());
System.out.println(ois.readObject());
fis.close();
ois.close();
}catch(Exception e){/**/}
}
}
这是Serializable Student类代码:
class Student implements Serializable{
private transient final int id;
private transient static int marks;
private String name;
public Student(int id, int marks, String name){
this.id = id;
this.marks = marks;
this.name = name;
}
public Student(){
id=0;
}
@Override
public String toString(){
return (this.name + this.id + this.marks);
}
}
带有transient关键字的代码输出.
ABC04
DEF04
输出没有临时关键字.
ABC34
DEF64
你能解释为什么它工作正常吗?有没有错误?
最后什么应该是具有final关键字的瞬态行为?
解决方法:
你的问题有点与此重复:
> final-transient-fields-and-serialization
> a-transient-final-field-used-as-a-lock-is-null
A final field must be initialized either by direct assignment of an initial value or in the constructor. During deserialization, neither of these are invoked, so initial values for transients must be set in the ‘readObject()’ private method that’s invoked during deserialization. And for that to work, the transients must be non-final.
和
Any field that is declared transient is not serialized. Moreover, according to this blog post, field values are not even initialized to the values that would be set by a default constructor. This creates a challenge when a transient field is final.
至于你的测试结果:
Code output with transient keyword.
ABC04 DEF04
Output without transient keyword.
ABC34 DEF64
短暂的
显然,瞬态字段(第4个字符)未被序列化/反序列化(ABC34-> ABC04和DEF64-> DEF04)
静态的
静态字段(第5个字符)也没有被反序列化!这只是因为您在同一个内存空间中执行操作,静态字段保留在所有实例中.因此,当您在学生上设置静态字段,然后反序列化另一个学生时,静态字段当然仍然具有相同的值!
这也解释了为什么在测试中首先将静态字段设置为2和
然后4,但只打印4.在这种情况下,与序列化无关,只是静态字段行为.
内容总结
以上是互联网集市为您收集整理的序列化Java中的最终瞬态如何工作全部内容,希望文章能够帮你解决序列化Java中的最终瞬态如何工作所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。