Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This compliant solution uses an enum and adds a custom readResolve() method that replaces the deserialized instance with a reference to the appropriate singleton from the current execution. More complicated cases may also require custom writeObject() or readObject() methods in addition to (or instead of) the custom readResolve() method.

Code Block
bgColor#ccccff
Classpublicpublic enum NumberEnumSingletonClass extends NumberNumberEnum {
  INSTANCE;
  NumberData number = new NumberData();
More information on correctly handling singleton classes is available in therule MSC07-J, “Prevent multiple instantiations of singleton objects.”
class SingletonClass extends Number {
   Exception {
  // ...
  private protected final Object readResolve() throws NotSerializableException {
    return INSTANCE;
  }
}

public class NumberData extends Number {
  // ...
}

This compliant solution uses composition over extension of the Number class. More information on singleton classes is available in rule MSC07-J. Prevent multiple instantiations of singleton objects.

Noncompliant Code Example

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="decf5954ca929020-52c10c39-42fa4582-9e0d9ad6-6760068247a45c359c884eae"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

Class Object, Class Hashtable

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0c61b89827a08fe5-12ca99e2-449f413c-a08482c5-37bbc964acd0f0152b40be0d"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. Bibliography#Bloch 08]]

Item 75, Consider using a custom serialized form

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="89ab5417ee5d4ec1-81f4afc7-48e54c2b-842292e3-7aa68e282840a4cdb3d8fb85"><ac:plain-text-body><![CDATA[

[[Greanier 2000

AA. Bibliography#Greanier 00]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="435ee9dfd2b8780a-90bf9720-491043f9-9269a070-33a77e6d2a0dd10c79a49cf2"><ac:plain-text-body><![CDATA[

[[Harold 1999

AA. Bibliography#Harold 99]]

Chapter 11, Object Serialization, Validation

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9eb643ba631b1008-af090ae4-457d489d-abb99611-57b10efd72c003d57d81f28c"><ac:plain-text-body><![CDATA[

[[Hawtin 2008

AA. Bibliography#Hawtin 08]]

Antipattern 8. Believing deserialisation is unrelated to construction

]]></ac:plain-text-body></ac:structured-macro>

...