I’m having issues with downcasting in JAXB with classes that are self-referential.
My setup:
@XmlRootElement
class IdentifiableObject {
@XmlID
@XmlAttribute
String id;
@XmlAttribute
String name;
}
@XmlRootElement
class Node extends IdentifiableObject {
@XmlElement
@XmlJavaAdapter(SimpleAdapterThatJustDowncastsToIdentifiableObject.class)
Node parent;
@XmlElement
String aField;
}
I have done this with plenty of other objects, and it works fine. But when I’m using a class that refers to itself, it doesn’t work.
Is there something I can do to fix this? I know using XmlID/XmlIDREF kinda solves the problem, but I really want more than just a simple ref (I want id and name from identifiable)
To clarify, this is what I get:
<nodes>
<node id="49ad1cb6-f6fe-47f9-a544-4a1c6337c4a5" name="Node 1">
<aField>This is Node 1</aField>
</node>
<node id="0a1d1895-49e1-4079-abc1-749c304cc5a2" name="Node 2">
<parent xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="node" id="49ad1cb6-f6fe-47f9-a544-4a1c6337c4a5" name="Node 1">
<aField>This is Node 1</aField>
</parent>
<aField>This is Node 2</aField>
</node>
</nodes>
And this is what I want:
<nodes>
<node id="49ad1cb6-f6fe-47f9-a544-4a1c6337c4a5" name="Node 1">
<aField>This is Node 1</aField>
</node>
<node id="0a1d1895-49e1-4079-abc1-749c304cc5a2" name="Node 2">
<parent id="49ad1cb6-f6fe-47f9-a544-4a1c6337c4a5" name="Node 1"/>
<aField>This is Node 2</aField>
</node>
</nodes>
UPDATE: just a note here, schemagen actually does the correct thing. So it might be a bug in the JAXB RI.
Regards,
Morten
You do not require an
XmlAdapterfor your use case. You can solve the issue by marking theIdentifiableObjectclass with@XmlTransient:Nodes
Node
IdentifiableObject
Demo
Input/Output
For More Information