private Element serializeBean(Object bean) {
try {
return inspectBean(bean);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.toString());
}
}
private Element inspectBean(Object bean)
throws
IntrospectionException,
IllegalAccessException,
InvocationTargetException {
BeanInfo info = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] properties = info.getPropertyDescriptors();
Element root = new Element(info.getBeanDescriptor().getName());
for (int i = 0; i < properties.length; i++) {
Class type = properties[i].getPropertyType();
String name = properties[i].getName();
Method m = properties[i].getReadMethod();
if (m != null) {
Object value = m.invoke(bean, null);
if (value == null)
value = new String("");
root = serializeProperty(name, value, root);
}
}
return root;
}
private Element serializeProperty(
String name,
Object value,
Element baseElement) {
try {
Class c = value.getClass();
Package p = c.getPackage();
if (value instanceof Collection) {
Collection col = (Collection) value;
Element list = new Element(name);
for (Iterator i = col.iterator(); i.hasNext();)
list = serializeProperty("item", i.next(), list);
baseElement.addContent(list);
} else if (value instanceof Map) {
Map col = (Map) value;
Element list = new Element(name);
for (Iterator i = col.keySet().iterator(); i.hasNext();) {
String keyName = (String) i.next();
list = serializeProperty(keyName, col.get(keyName), list);
}
baseElement.addContent(list);
} else if (p == null) {
} else if (p != null && p.getName().equals("java.lang")) {
Element e = new Element(name);
e.addContent(value.toString());
baseElement.addContent(e);
} else {
Element e = inspectBean(value);
baseElement.addContent(e);
}
} catch (Exception exc) {
exc.printStackTrace();
}
return baseElement;
}