反序列化的对象字段为空

时间:2017-01-10 23:20:06

标签: java android serialization

我已经成功序列化了我的自定义对象,但是当我反序列化它时会发生这种情况:

- 自定义对象是非空的

- 所有字段均为NULL

我知道我已经成功序列化了自定义对象,因为我已经阅读了序列化文件,看起来很好。

这是我的代码:

public class Preferences implements Serializable {

private static Preferences instance;
public static final long serialVersionUID = 3358037972944864859L;
public String accessToken;

protected Object readResolve() {
    return getInstance();
}

private Preferences() {

}

private synchronized static void synchronize() {
    if(instance == null) {
        instance = new Preferences();
    }
}

public static Preferences getInstance() {
    if(instance == null) {
        Preferences.synchronize();
    }

    return instance;
}

public void save(File file) {
    try {
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream out = new ObjectOutputStream(fos);

        Preferences tempInstance = Preferences.getInstance();

        out.writeObject(tempInstance);
        out.close();
        fos.close();
    }catch(IOException e) {
        e.printStackTrace();
    }
}

public void load(File file) {
    try {
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream in = new ObjectInputStream(fis);

        if(file.length() > 0) {
            Preferences tempInstance = (Preferences) in.readObject();

            Log.e("", String.valueOf(tempInstance == null)); //prints FALSE
            Log.e("", String.valueOf(tempInstance.accessToken == null)); //prints TRUE
        }

        in.close();
        fis.close();
    }catch(IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}
}

这是我的测试代码:

public class CustomActivity extends AppCompatActivity {

private File dir = new File(Environment.getExternalStorageDirectory(), ".app");
private File backup = new File(dir, "backup.ser");

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    Log.e("APPLICATION", "START");

    super.onCreate(savedInstanceState);

    if(this instanceof ActivityLogin) {
        if(!dir.exists()) {
            dir.mkdirs();
        }

        Preferences.getInstance().load(backup);
    }
}

@Override
protected void onUserLeaveHint() {
    super.onUserLeaveHint();

    try {
        backup.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Preferences.getInstance().save(backup);

    Log.e("APPLICATION", "STOP");
}

}

对可能存在什么问题的任何想法?

1 个答案:

答案 0 :(得分:3)

你班上有这个方法:

protected Object readResolve() {
    return getInstance();
}

这告诉序列化机制:无论何时反序列化Preferences实例,请将其替换为getInstance()返回的实例。因此,如果您调用load()并且Preferences的实例具有null accessToken,则反序列化的首选项也将具有null accessToken,因为它们是同一个对象。

添加

System.out.println(tempInstance == this);

到您的日志记录语句(或者您在android中用于记录的任何内容),您将看到。