Skip to main content

JAXB Singletons Made Easy

Posted by mkarg on January 14, 2012 at 9:22 AM PST

You want JAXB to unmarshal singletons? You already spent lots of time coding rather complex workarounds applying XmlAdapters and afterUnmarshal callbacks? The solution is astonishingly simple. Possibly so simple that nobody in the JAXB team ever thought it would be necessary to put the word "singleton" somewhere next to the JavaDocs for this... Anyways, here is the solution:

import javax.xml.bind.annotation.*;
@XmlRootElement @XmlType(factoryMethod="createMySingleton")
public class MySingleton {
  private MySingleton() {}
  @Override
  public boolean equals(Object obj) {
    return obj instanceof MySingleton;
  }
  @Override
  public int hashCode() {
    return 0;
  }
  public static final MySingleton MY_SINGLETON = new MySingleton();
  @SuppressWarnings("unused")
  private static MySingleton createMySingleton() {
    return MY_SINGLETON;
  }
}

Hope this is of any use for you.

A collection of all my blog entries can be found on my web site Head Crashing Informatics.