2

I have a following Singleton class:

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() {

    }
}

I deserialize as follow:

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());    

My question: How can I deserialize this directly to a Singleton?

t0tec
  • 330
  • 4
  • 16
  • What do you mean? You are deserialising into the singleton. – Boris the Spider Mar 30 '14 at 16:24
  • Well If I change User.class to AuthenticatUser.class it isn't making an instance, how to solve that? Just put instance = this or instance = getInstance() in private constructor? – t0tec Mar 30 '14 at 16:35
  • 1
    I think you have stumbled across the exact reason why [singletons are evil](http://stackoverflow.com/a/138012/2071828)... – Boris the Spider Mar 30 '14 at 16:37
  • Ok, I think that is lecture a bit above my head. Well I just need to store the User instance in my application so I can access it from multiple places when needed, So Singleton was the only option I found. Will have to rethink about this. – t0tec Mar 30 '14 at 16:50

1 Answers1

2

Since Gson uses reflection - it ignores the private/public instructions which are checked at compile time, and therefore it can create a new object. However, if you want this object to be your singleton's instance, you will need to manually set it. here is an example:

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();
Oren
  • 31
  • 1
  • 5