当我在我的类中使用 Serialized 并在 Scanner 中使用瞬态时,如何解决 NullPointerException?
我想知道我需要做什么来解决这个错误。 由于在我想要序列化的类中使扫描仪瞬态,我现在得到一个空指针异常,其中使用扫描仪(in)的第一个实例。
即in.next();
这是我第一次在工作中使用 Serialized。我已将所有顶级类设为可序列化。
我还想知道是否需要对我的数据结构(例如数组、数组列表等)进行任何操作。哪些内容需要标记为瞬态?
非常感谢任何帮助
I was wondering what things I would need to do to resolve this error.
Since making the scanner transient in my class that I want to serialize, I now get a nullpointerexception where the first instance of where the scanner (in) is used.
i.e in.next();
It is the first time I am using Serializable in my work. I have made all my top level classes Serializable.
I was wondering also if anything has to be done to my data structures such as arrays, arraylists etc. What things would need to be tagged as transients?
Any help much appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
序列化对象时,不会保留瞬态字段中的值。一种解决方案是实现一个
writeObject
方法,该方法在反序列化对象后重新初始化瞬态字段,如下所述:http://java.sun.com/developer/technicalArticles/Programming/serialization/但是,有一个
扫描仪
可序列化类中的对象听起来有点奇怪。您可能应该将其分为两个类 - 一个可序列化的类,其中包含要序列化的数据,另一个类则执行用户界面或文件读取或您使用扫描仪执行的任何操作。Values in transient fields are not kept when you serialize an object. One solution is to implement a
writeObject
method that reinitializes transient fields after an object is deserialized, as described here: http://java.sun.com/developer/technicalArticles/Programming/serialization/However, having a
Scanner
object in a serializable class sounds a bit strange. You should probably split this into two classes - a serializable class that contains the data you want to serialize, and another class that does the user interface or file reading or whatever it is you are doing with aScanner
.