Get JAX-B to work with circular dependencies.

When serializing objects that have circular dependencies with JAX-B the framework throws a CyclicDependencyDetected exception. For example there are two classes A and B. Class A has a property x of type B and class B has a list y of As. Using the annotations <code>@XmlElementRef B x</code> in class A and <code>@XmlWrapperElement("ys") @XmlElementRef List&lt;A> y</code> in class B will throw the aforementioned exception. How to serialize object graphs like these?
1 answer


This solution only works if your classes contain a property that acts as an ID (i.e. annotated with @XmlID).

One of the classes has to implement the interface CycleRecoverable which provides the sole method Object onCycleDetected(Context ctx).
When overriding this method return an object that only contains the ID of that class e.g.:
class A implements CycleRecoverable {
public Object onCycleDetected(Context ctx) { return new A(; }