Thursday, September 18, 2008

Solution to the issue with List's in wsimport generated POJO classes

This topic is in extension to " It is not necessary to use wsimport generated POJO Files " post on this blog. Lets consider that our Employee class has another property called addresses . This addresses property is a List of strings. So our modified Employee shall look like:
import java.util.List;

public class Employee {
 private int age;
 private String name;
 private List<String> addresses;

 public Employee() {
 }

 public Employee(int age, String name, List<String> addresses) {
  super();
  this.age = age;
  this.name = name;
  this.addresses = addresses;
 }
 
 //write getter setter for properties to comply to Java Bean/POJO standard
}
and the Web Method is:
@WebMethod
 public Employee printEmployee(Employee e) {
  System.out.println(e.getName() + " - " + e.getAge() + " - " e.getAddresses);
  return e;
 }
As a result of generating the client using wsimport, the generated Employee looks like:
@XmlAccessorType(XmlAccessType.FIELD) 
 @XmlType(name = "employee", propOrder = {  "addresses",  "age",  "name" }) 
 public class Employee {  
  @XmlElement(nillable = true)  
  protected List addresses;  
  protected int age;  
  protected String name;
 }

and strangely enough there is no setter method for the list of addresses. There is a clear explanation for the same in the comments above the getter for the addresses property as:
This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for the addresses property.
Solution: But this doesn't mean that this is a dead end. As mentioned in the original blog, you can replace the generated Employee class with the one that you used in the Web Service. With that you shall have the setter method for addresses list and the client invokes the Web Service perfectly.

1 comment:

  1. Not sure if this is the way to solve this problem as the client never knows whats required at the server so he/she won't be able to change the objects in such a way and as a matter of fact he/she should not change the objects, unless there is a compelling reason to do so.

    ReplyDelete