Friday, May 7, 2010

JAXB immutable objects

Yesterday, we faced a weird problem. Apache cxf was not generating schema definitions for immutable objects. Looking a bit deeper, the problem was with JAXB, the default databinding technology for apache cxf. Googled "jaxb immutable", and found out i was not alone facing the problem, but the solution of using the "no-args constructor" did not work me. Finally after spending a good 2 hrs on it, finally found the solution. You need to add a no-args constructor AND add @XmlAccessorType(XmlAccessType.FIELD) annotation to the class.

The following object did NOT work -

public class CreditCardVO implements Serializable {
private Long ccNumber;
private String ccName;

public CreditCardVO(Long ccNumber, String ccName) {
this.ccNumber = ccNumber;
this.ccName = ccName;
}

public Long getCcNumber() {
return ccNumber;
}

public String getCcName() {
return ccName;
}

}

When i added the no-args constructor and the annotations it worked!

@XmlAccessorType(XmlAccessType.FIELD)
public class CreditCardVO implements Serializable {
private Long ccNumber;
private String ccName;

public CreditCardVO(Long ccNumber, String ccName) {
this.ccNumber = ccNumber;
this.ccName = ccName;
}

private CreditCardVO() {
// for JAXB's Magic
}

public Long getCcNumber() {
return ccNumber;
}

public String getCcName() {
return ccName;
}

}