0

How we can serialize/deserialize a class in java with keeping its singleton nature in the application. Suppose I have serialized a class on every re-deployment of my application with updated values which i want to deserialize later.

Anuj Panwar
  • 113
  • 7
  • 1
    Read this its how to prevent this https://www.geeksforgeeks.org/prevent-singleton-pattern-reflection-serialization-cloning/ – Thelouras Dec 27 '18 at 11:46
  • How about creating a DTO for it? – Sofo Gial Dec 27 '18 at 11:46
  • 1
    A [relevant answer](https://stackoverflow.com/a/71399/1273080) suggests simply using a single-valued `enum`. This provides the serialization machinery for free and makes sure there are no shenanigans. – Petr Janeček Dec 27 '18 at 12:22

1 Answers1

1

yes you can do it my implementing

1) instance of the class as static

public static Singleton instance = new Singleton();

2) you have to add private constructor

private Singleton()  
{ 
    // private constructor 
} 

3) You have to declare method by which you can access the declared obj

// implement readResolve method 
protected Object readResolve() 
{ 
    return instance; 
} 
NPE
  • 429
  • 2
  • 16
  • 1
    maybe yes , but it is not your solutions , you can just leave a comment with the link to read the whole answer – Thelouras Dec 27 '18 at 11:51
  • I had implemented the same in my prodcut with the same logic, and bottom line is like it will solve the problem :) – NPE Dec 27 '18 at 11:53
  • 2
    This doesn't answer the question because it doesn't give the singleton instance the data that was deserialized from the file. – DodgyCodeException Dec 27 '18 at 12:12
  • 1
    I dont think so,this is what I wrote and worked for me, BTW in my solution am not talking about deserializatin of object anywhere ,any way if you think you can have something bettor to say yes please you can – NPE Dec 27 '18 at 12:16
  • The question asks how we can serialize/deserialize a singleton class, which will have updated values that need to be deserialized later. – DodgyCodeException Dec 27 '18 at 13:20