Valid Java 77 For instance control, prefer enum types to readResolve

Source: Internet
Author: User

The readResolve feature allows you to substitute another instance for the one created by readObject [Serialization, 3.7].

If the class of an object being deserialized definesReadResolve methodWith the proper declaration, this methodIs invoked on the newly created object after it is deserialized. The object reference returned by this method is thenReturned in place of the newly created object. In most uses of this feature, no reference to the newly created object is retained, so it immediately becomes eligible for garbage collection.

Public class Elvis implements Serializable {

/**

* The version UID for the serial version object.

*/

Private static final long serialVersionUID = 4285474589310444336l;

Public static final Elvis INSTANCE = new Elvis ();

Private Elvis (){

}

// ReadResolve for instance control-you can do better!

Private Object readResolve (){

// Return the one true Elvis and let the garbage collector take care of the Elvis impersonator.

Return INSTANCE;

}

Public static void main (String [] args ){

ByteArrayOutputStream OS = new ByteArrayOutputStream ();

ObjectOutputStream oos;

Try {

Oos = new ObjectOutputStream (OS );

Oos. writeObject (Elvis. INSTANCE );

Oos. close ();

ByteArrayInputStream is = new ByteArrayInputStream (OS. toByteArray ());

ObjectInputStream ois = new ObjectInputStream (is );

Elvis e = (Elvis) ois. readObject ();

System. out. printf ("Elvis is % s the one used before? ",

E = Elvis. INSTANCE? "": "Not ");

Ois. close ();

} Catch (IOException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

} Catch (ClassNotFoundException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

}

}

Note

If you depend on readResolve for instance control, all instance fields with object reference types must be declared transient.If a singleton contains a nontransient object reference field,The contents of this field will be deserialized before the singleton's readResolve method is run.

A demo for attack to secure a reference to the deserialized object before its readResolve method is run.

First, write a "stealer" class thatHas both a readResolve method and an instance field that refers to the serialized singleton in which the stealer "hides ."In the serialization stream,Replace the singleton's nontransient field with an instance of the stealer.You now haveCircularity:The singleton contains the stealer and the stealer refers to the singleton.

Because the singleton contains the stealer, the stealer's readResolve method runs first when the singleton is deserialized. as a result, when the stealer's readResolve method runs, its instance field still refers to the partially deserialized (and as yet unresolved) singleton.

The stealer's readResolve method copies the reference from its instance field into a static field, so that the reference can be accessed after the readResolve method runs. the method then returns a value of the correct type for the field in which it's hiding. if it didn't do this, the VM wocould throw a ClassCastException when the serialization system tried to store the stealer reference into this field.

// Broken singleton-has nontransient object reference field!

Public class Elvis implements Serializable {

Private static final long serialVersionUID = 1L;

Public static final Elvis INSTANCE = new Elvis ();

Private Elvis (){

}

PrivateString [] favoriteSongs = {"Hound Dog", "Heartbreak Hotel"}; // favorite field

Public void printFavorites (){

System. out. println (Arrays. toString (favoriteSongs ));

}

Private Object readResolve () throws ObjectStreamException {

Return INSTANCE;

}

}

Public class ElvisStealer implements Serializable {

Static Elvis impersonator;

Private Elvis payload;

Private Object readResolve (){

// Save a reference to the "unresolved" Elvis instance

Impersonator = payload;

// Return an object of correct type for favorites field

Return new String [] {"A Fool Such as I "};

}

Private static final long serialVersionUID = 0;

}

You cocould fix the problem by declaring the favorites field transient, but you're better off fixing it by making Elvis a single-element enum type (Item 3 ).

// Enum singleton-the preferred approach

PublicEnumElvis {

INSTANCE;

Private String [] favoriteSongs = {"Hound Dog", "Heartbreak Hotel "};

Public void printFavorites (){

System. out. println (Arrays. toString (favoriteSongs ));

}

}

The accessibility of readResolve is significant.

If you place a readResolve method on a final class, it shoshould be private.

If you place a readResolve method on a nonfinal class, you must carefully consider its accessibility.

If it is private, it will not apply to any subclasses.

If it is package-private, it will apply only to subclasses in the same package.

If it is protected or public, it will apply to all subclasses that do not override it.

If a readResolve method is protected or public and a subclass does not overriden it, deserializing a serialized subclass instance will produce a superclass instance, which is likely to cause a ClassCastException.

Summary

You shoshould use enum types to enforce instance control invariants wherever possible. if this is not possible and you need a class to be both serializable and instance-controlled, you must provide a readResolve method and ensure that all of the class's instance fields are either primitive or transient.

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.