我有以下单例课程:
public class AuthenticatedUser extends User {
private volatile static AuthenticatedUser instance;
public static AuthenticatedUser getInstance() {
if (instance == null) {
synchronized (AuthenticatedUser.class) {
instance = new AuthenticatedUser();
}
}
return instance;
}
private AuthenticatedUser() {
}
}
我反序列化如下:
Reader reader = new InputStreamReader(entity.getContent());
User user = new Gson().fromJson(reader, User.class);
AuthenticatedUser aus = AuthenticatedUser.getInstance();
aus.setId(user.getId());
aus.setUsername(user.getUsername());
aus.setPassword(user.getPassword());
aus.setEmail(user.getPassword());
aus.setFullName(user.getFullName());
我的问题:如何直接将此序列化为Singleton?
最佳答案
由于Gson使用反射-它会忽略在编译时检查的私有/公共指令,因此可以创建一个新对象。但是,如果要将此对象作为单例的实例,则需要手动设置它。
这是一个例子:
Gson gson = new Gson();
// Serializing
AuthenticatedUser user = AuthenticatedUser.getInstance();
user.setUsername("me");
String json = gson.toJson(user);
// Desesializing
AuthenticatedUser user2 = gson.fromJson(json, AuthenticatedUser.class);
user2.setInstance(); // this is important!
String username = AuthenticatedUser.getInstance().getUsername();