反序列化Singleton

时间:2018-03-18 10:53:19

标签: java serialization singleton deserialization singleton-methods

    //Singleton
    public class MainList implements Serializable {
            private static MainList instance = new MainList();
            private MainList() {}

            public static MainList getInstance() {
                return instance;
            }
        }

    //Trying to deserialize..
    public MainWindow() {
        //Importing the latest version if it exists in path
        MainList mainListObj = MainList.getInstance();
        try {
            FileInputStream fis = new FileInputStream(path);
            ObjectInputStream oin = new ObjectInputStream(fis);
            mainListObj = (MainList) oin.readObject(); //HERE//////
        }
        catch (Exception exc) {
            return;
        }
    }

MainList类的Singleton-Object被序列化&可以通过路径找到。

在行// HERE ///对象成功反序列化为mainListObj, 但它是本地的..

如何让它全球化?我认为它可以通过连接getInstance方法来解决..某些方式..

1 个答案:

答案 0 :(得分:0)

您的案例不是singleton

在您的情况下,您只需提供一个setter。

static void setInstance(MainList newInstance) {
 instance = newInstance;
}

MainList.setInstance(mainListObj);