Creating immutable objects using JAXB

niteen22 picture niteen22 · Jun 14, 2012 · Viewed 7.3k times · Source

I am using JAXB to create Java objects from XSD file. I am creating immutable wrappers to conceal objects generated by JAXB (earlier I was updating JAXB objects to implement immutable interface and return interface to client. But realised it is bad to change auto generated classes, hence using wrappers)

Currently I am returning these immutable wrappers to client app. Is there any option so that auto generated classes will be immutable and it will avoid extra work of creating immutable wrappers. Any other approach is encouraged.

  • Thanks

Answer

user2062595 picture user2062595 · Feb 11, 2013

as of JSR-133 (Java 1.5 dependency) you can use reflection to set uninitialized final variables. so you can init to null in the private constructor and use JAXB + immutable cleanly without any XMLAdapter.

example from https://test.kuali.org/svn/rice/sandbox/immutable-jaxb/ , got this from a comment on Blaise's blog http://blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html#comment-form_584069422380571931

package blog.immutable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="customer")
@XmlAccessorType(XmlAccessType.NONE)
public final class Customer {

    @XmlAttribute
    private final String name;

    @XmlElement
    private final Address address;

    @SuppressWarnings("unused")
    private Customer() {
        this(null, null);
    }

    public Customer(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public Address getAddress() {
        return address;
    }

}