[英]Why does serialization work without implementing Serializable
Is it mandatory to implement Serializable class when serializing a class .I tried to put object data into file with and without serializable implementation and found absolutely no difference. 序列化一个类时是否必须实现Serializable类。我尝试将对象数据放入有或没有可序列化实现的文件中,发现绝对没有区别。
import java.io.*;
import java.net.*;
public class SerializableTest {
int a= 10;
String test="Serialize test";
public static void main(String [] args){
SerializableTest test =new SerializableTest();
test.save();
}
public void save(){
try{
FileOutputStream fs = new FileOutputStream("save.res");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(test);
os.close();
}
catch (Exception ex ){
System.out.println("Error in opening or saving file");
}
System.out.println("Complete");
}
}
import java.io.*;
import java.net.*;
public class SerializableTest **implements Serializable**{
int a= 10;
String test="Serialize test";
public static void main(String [] args){
SerializableTest test =new SerializableTest();
test.save();
}
public void save(){
try{
FileOutputStream fs = new FileOutputStream("save.res");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(test);
os.close();
}
catch (Exception ex ){
System.out.println("Error in opening or saving file");
}
System.out.println("Complete");
}
}
In both cases program ran fine and contents of save.res looked absolutely similar. 在这两种情况下,程序都可以正常运行,并且save.res的内容看上去绝对相似。
Serializable
should ideally be implemented by the object that needs to be serialized. 理想情况下,可
Serializable
应该由需要序列化的对象实现。 String
implements Serializable
. String
实现Serializable
。 You are serializing a String
object. 您正在序列化一个
String
对象。 You are not serializing SerializableTest
. 您没有序列化
SerializableTest
。
In other words, it does not matter if SerializableTest
implements Serializable
or not since SerializableTest
is not the object that is being serialized. 换句话说,
SerializableTest
实现Serializable
并不重要,因为SerializableTest
不是要序列化的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.