Saturday, August 15, 2009

Return List of embedded objects in complex java object

Class Employee{
int id;
Address address;
String name;
}

Class Address{
String city;
String state;
ZipCode zip;
}

Class ZipCode{
String zipcode;
String extension;
}

List employees = ...... list of employees

If i need to retrieve all the zipcodes at which the employees are present.

Before knowing JXpath, I created a small recursive function which retrieves the information of each field. Later converted the object to xml and used xpath and got the values.

JXPath helps you ease you work

public static List returnList(List objList, String xPathName){
JXPathContext jxPathContext = null;
List returnedList = new ArrayList();
for(Object obj:objList){
jxPathContext = JXPathContext.newContext(obj);
returnedList.add(jxPathContext.getValue(xPathName));
}
return returnedList;
}