package test;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class XmlReflector {
private Class sourceClass;
private BeanInfo beanInfo;
private String name;
XmlReflector(Class sourceClass, String name) throws Exception {
this.sourceClass = sourceClass;
this.name = name;
beanInfo = Introspector.getBeanInfo(sourceClass);
}
public String convertToXml(Object o) throws Exception {
StringBuffer returnValue = new StringBuffer("");
if (o.getClass().isAssignableFrom(sourceClass)) {
PropertyDescriptor[] pd = beanInfo.getPropertyDescriptors();
if (pd.length > 0) {
returnValue.append("<" + name + ">");
for (int i = 0; i < pd.length; i++) {
returnValue.append(getProp(o, pd[i]));
}
returnValue.append("</" + name + ">");
} else {
returnValue.append("<" + name + "/>");
}
} else {
throw new ClassCastException("Class " + o.getClass().getName()
+ " is not compatible with " + sourceClass.getName());
}
return returnValue.toString();
}
private String getProp(Object o, PropertyDescriptor pd) throws Exception {
StringBuffer propValue = new StringBuffer("");
Method m = pd.getReadMethod();
Object ret = m.invoke(o);
if (null == ret) {
propValue.append("<" + pd.getName() + "/>");
} else {
propValue.append("<" + pd.getName() + ">");
propValue.append(ret.toString());
propValue.append("</" + pd.getName() + ">");
}
return propValue.toString();
}
}