【发布时间】:2017-01-10 23:20:05
【问题描述】:
我已经成功序列化了我的自定义对象,但是当我反序列化它时会发生这种情况:
-自定义对象不为空
-所有字段为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");
}
}
对可能出现的问题有任何想法吗?
【问题讨论】:
-
你没有对读取的对象做任何事情。您的加载方法应该是静态的,并且应该返回反序列化的实例。
instance和this是两个不同的、不相关的对象。 -
在 load() 完成后,我正在对实例对象做一些事情,但在 load() 中,实例不为空,而其所有字段都为空。请看我的编辑。 @JBNizet
-
发布一个完整的最小示例来重现错误。我们不知道您在序列化和反序列化什么。
-
@fabian 我已经解决了这个问题,但同样的问题。查看我的编辑。
-
@JBNizet 已发布完整代码。
标签: java android serialization