Object Serialization Single Example

Source: Internet
Author: User
Tags object serialization serialization

When serializing and deserializing, if you want to ensure that the object is unique (for example, a single case pattern), you need to be extra careful, usually in implementing a single and type-safe enumeration that occurs. In this case, the default serialization mechanism does not apply.

Public final class Singelton implements Serializable {

Private Singelton () {

}

private static final Singelton INSTANCE = new Singelton ();

public static Singelton getinstance () {

return INSTANCE;

}

}

If a single instance object is serialized, and the object is deserialized from memory

ObjectOutputStream out = new ObjectOutputStream (New FileOutputStream ("Test.dat"));
Out.writeobject (SINGLE1);

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Test.dat"));

Singelton Newsingle = (Singelton) in.readobject ();

At this time the Newsingle and Single1 is completely different, is a brand-new object, destroyed the single case principle.

To solve this problem, you need to add a special serialization Method Readresolve () method to the class. If the method is defined, it is called after the object is serialized.

Public final class Singelton implements Serializable {

Private Singelton () {

}

private static final Singelton INSTANCE = new Singelton ();

public static Singelton getinstance () {

return INSTANCE;

}

Private Object Readresolve () throws Objectstreamexception {

return INSTANCE;

}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.