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.
Immutable class in java means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. We can create our own immutable class as well.
A Java immutable object must have all its fields be internal, private final fields. It must not implement any setters. It needs a constructor that takes a value for every single field. Immutable objects come in handy in multi-threaded environments and in streams.
Example to create Immutable class It have one final datamember, a parameterized constructor and getter method. The above class is immutable because: The instance variable of the class is final i.e. we cannot change the value of it after creating an object. The class is final so we cannot create the subclass.
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;
}
}
You can use these XJC compiler plugins to directly generate immutable classes:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With