JAXB Singletons Made Easy
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 true;}
@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.
- Login or register to post comments
- Printer-friendly version
- mkarg's blog
- 1944 reads





