Another one of these by type rather than instanceof or if-else. Joshua Bloch seems to have the answer: "If a typesafe enum class has methods whose behavior varies significantly from one class constant to another, you should use a separate private nested class or anonymous inner class for each constant. This allows each constant to have its own implementation of each such method, and automatically invokes the correct implementation. The alternative is to structure each such method as a multi-way branch that behaves differently depending on the constant on which it's invoked. This alternative is ugly, error prone, and likely to provide performance that is inferior to that of the virtual machine's automatic method dispatching."
Object Input Classes "Note – The readResolve method is not invoked on the object until the object is fully constructed, so any references to this object in its object graph will not be updated to the new object nominated by readResolve. However, during the serialization of an object with the writeReplace method, all references to the original object in the replacement object’s object graph are replaced with references to the replacement object. Therefore in cases where an object being serialized nominates a replacement object whose object graph has a reference to the original object, deserialization will result in an incorrect graph of objects. Furthermore, if the reference types of the object being read (nominated by writeReplace) and the original object are not compatible, the construction of the object graph will raise a ClassCastException."
Exploring Enums: The Wait Is Finally Over "Spare the serialization: Enum serialization isn't like the normal one you have seen. The process by which enum constants are serialized cannot be customized. Any class-specific writeObject and writeReplace methods defined by enum types are ignored during serialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored - all enum types have a fixed serialVersionUID of 0L. Again, this shouldn't concern you too much. Let the language take care of the specifics."
No comments:
Post a Comment