Java中多个类可以序列化同一个对象吗?
我正在将 ArrayList 序列化为 2 个类:
private void serializeQuotes(){
FileOutputStream fos;
try {
fos = openFileOutput(Constants.FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotesCopy);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void deserializeQuotes(){
try{
FileInputStream fis = openFileInput(Constants.FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
quotesCopy = (ArrayList<Quote>) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
让我们假设:
1. Class A serializes Quotes
2. Class B deserializes Quotes
3. Class B adds stuff to Quotes
4. Class B serializes Quotes
我可以安全地假设 Quotes 将被更新并且在两个类之间同步吗?
I am serializing an ArrayList in 2 classes:
private void serializeQuotes(){
FileOutputStream fos;
try {
fos = openFileOutput(Constants.FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(quotesCopy);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void deserializeQuotes(){
try{
FileInputStream fis = openFileInput(Constants.FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
quotesCopy = (ArrayList<Quote>) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
Let's assume:
1. Class A serializes Quotes
2. Class B deserializes Quotes
3. Class B adds stuff to Quotes
4. Class B serializes Quotes
Can I safely assume Quotes will be updated and is in sync between the two classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从你的描述来看,没有。
序列化一个对象基本上只是将其快照写入流中,以便可以将其保存到磁盘或传输到其他地方并读取。不涉及数据同步。更改已反序列化的对象不会对其最初序列化的对象产生任何影响...没有任何链接。简单地将对象序列化到共享文件也不会导致任何类型的同步,因为在写入文件时,使用该文件的任何内容都不会自动读取该文件并同步其状态,而无需添加代码来近似该效果你自己。
From what you've described, no.
Serializing an object basically just writes a snapshot of it to a stream so that it can be saved to disk or transferred elsewhere and read. There is no syncing of data involved. Changing an object you've deserialized will have no effect on the object it was originally serialized from... there's no link whatsoever. Simply serializing the object to a shared file won't cause any kind of syncing either, since nothing that is using the file is going to automatically read the file and synchronize its state when the file is written to without you adding code to approximate that effect yourself.