java 如何实现可序列化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28788992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement Serializable?
提问by Mostafa M Awad
How should I implement
the Serializable
interface?
我implement
的Serializable
界面应该如何?
I have a class
Student
, and need to be able to save it to disk. For my homework, I have to serialize five different Student
objects and save them to file.
我有一个class
Student
, 并且需要能够将它保存到磁盘。对于我的作业,我必须序列化五个不同的Student
对象并将它们保存到文件中。
class Student {
String mFirstName;
String mSecondName;
String mPhoneNumber;
String mAddress;
String mCity;
Student(final String pFirstName, final String pSecondName, final String pPhoneNumber, final String pAddress, final String pCity){
this.mFirstName = pFirstName;
this.mSecondName = pSecondName;
this.mPhoneNumber = pPhoneNumber;
this.mAddress = pAddress;
this.mCity = pCity;
}}
I've tried using ObjectOutputStream
to serialize a Student
, but it throws an error:
我试过用ObjectOutputStream
序列化 a Student
,但它抛出一个错误:
ObjectOutputStream lOutputStream = new ObjectOutputStream(new FileOutputStream("file.txt", true));
lOutputStream.write(new Student("foo","bar","555-1234","Flat 40","Liverpool"));
回答by DonatasD
The only thing you need to do is implement Serializable. The only thing you need to worry when implementing this interface is to make sure that all fields of such class, has implemented Serializable interface as well. In your case all fields are Strings and they already implement Serializable. Therefore, you only need to add implements Serializable. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Serializable.html
您唯一需要做的就是实现可序列化。实现此接口时,您唯一需要担心的是确保此类的所有字段也都实现了 Serializable 接口。在您的情况下,所有字段都是字符串,并且它们已经实现了可序列化。因此,您只需要添加implements Serializable。https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Serializable.html
public class Student implements Serializable {
String first;
String second;
String phone;
String cityAddress;
String cityStreet;
public Student(String s1, String s2, String s3, String s4, String s5) {
first = s1;
second = s2;
phone = s3;
cityAddress = s4;
cityStreet = s5;
}
}