xmlsoapjaxbmoxytype-erasure

How to avoid type erasue in JAXB, MOXY implementation while marshalling?


I have to marshall following class ;

@XmlRootElement(name = "SYSMessage")
@XmlAccessorType(XmlAccessType.FIELD)
public class Message<T> {

    @XmlPath("Personel")
    private Personel personel;

    @XmlPath("AccountType")
    private T accountType;

    ...

So in production I set generic Account type class with some object called "DebitAccount" I have to use generic type because debitAccount will change many times.

Message<DebitAccount> msg = new Msg<>();
DebitAccount dAccount= new DebitAccount();
msg.setAccountType(dAccount);

and when I marshalled class Message, I got the following xml result as account type; ... org.demo.blabla.DebitAccount@123123 ...

In DebitAccount class;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DebitAccount{

    @XmlPath("ID")
    private String id;

    @XmlPath("Visa")
    private String visaNo;

I figured out this is happening because of Type erasure. Moxy just cant simply understand that my object is DebitAccount. So it treats object as string. How can I make moxy understand my composite object.


Solution

  • You have to bind DebitAccount class to the same XML context of Message class using @XmlSeeAlso annotation. You can list multiple classes with curly braces. When using generic types (T or ?), you have to specify which classes are part of the same context.

    @XmlRootElement(name = "SYSMessage")
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlSeeAlso({DebitAccount.class})
    public class Message<T> { ... }