Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jaxb marshall abstract class instead of unique

Tags:

java

jaxb

I have the following relation:

Class A abstract;
Class B concrete extends A;
Class C has a one to one relation with B.

let us say

A a=new B();

if i marshal A it will be marshalled by the use of the xml data presented on B

<B>
</B>

but if we say

C c = new C();
c.setA(new B());.

i get:

<C>
<A>
</A>
</C>

but A is abstract so during unmarshalling an exception will be thrown. my problem how to let jaxb marshell the concrete instead of abstract class during the marshalling of C so the result of the xml file wil be:

<C>
<B>
</B>
<C>
like image 949
bob-cac Avatar asked Dec 04 '25 05:12

bob-cac


2 Answers

If you annotate with @XmlElementRef then it will match the value based on its @XmlRootElement annotation.

@XmlElementRef
private A a;
  • http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html
like image 145
bdoughan Avatar answered Dec 05 '25 22:12

bdoughan


You have to annote the Clacc C in this way

public class C{

@XmlElements({
    @XmlElement(name="B", type=B.class),
    @XmlElement(name="D", type=D.class),
    @XmlElement(name="E", type=E.class),
    @XmlElement(name="F", type=F.class),
    //....
   })    
  private A a;


 }
like image 28
Skizzo Avatar answered Dec 05 '25 22:12

Skizzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!