代码之家  ›  专栏  ›  技术社区  ›  Sheehan Alam

在Java中,多个类可以序列化同一个对象吗?

  •  0
  • Sheehan Alam  · 技术社区  · 15 年前

    我将ArrayList序列化为两个类:

    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将被更新,并且在两个类之间是同步的吗?

    1 回复  |  直到 15 年前
        1
  •  2
  •   ColinD    15 年前

    根据你的描述,没有。

    序列化对象基本上只是将其快照写入流中,以便将其保存到磁盘或传输到其他位置并读取。没有涉及数据同步。更改已反序列化的对象对最初从中序列化的对象没有影响。。。没有任何联系。简单地将对象序列化为共享文件也不会导致任何类型的同步,因为使用该文件的任何东西都不会在写入文件时自动读取该文件并同步其状态,而无需您自己添加代码来近似这种效果。