Friday, July 11, 2008
Dumping a JavaBean as name/value pairs ?
Sometimes it's useful to deeply dump out the properties of a complex JavaBean as name/value pairs, perhaps for debugging purposes, even when none of the toString methods of the classes involved are defined. This is especially the case when the JavaBean classes are written by a third party.
Now how would you go about doing that ?
How about using the Jarkarta commons-lang's ToStringBuilder.reflectionToString method ? It doesn't cut it, as it relies on the toString method of the individual classes involved.
How about XMLEncoder or XStream ? They work pretty nicely. However, by default XStream generates not just the public properties but all other fields as well. In both cases, the generated XML would need to be further transformed into name/value pairs.
Another way I can think of is to take advantage of the latest BeanSourceHandler SPI as a side effect of performing a deep clone via the open-source library Beanlib (beanlib-3.3.0beta18). What do I mean ? Here is an example:
Now how would you go about doing that ?
How about using the Jarkarta commons-lang's ToStringBuilder.reflectionToString method ? It doesn't cut it, as it relies on the toString method of the individual classes involved.
How about XMLEncoder or XStream ? They work pretty nicely. However, by default XStream generates not just the public properties but all other fields as well. In both cases, the generated XML would need to be further transformed into name/value pairs.
Another way I can think of is to take advantage of the latest BeanSourceHandler SPI as a side effect of performing a deep clone via the open-source library Beanlib (beanlib-3.3.0beta18). What do I mean ? Here is an example:
Object bean = ...
// Dump out the entire JavaBean
// when none of the toString methods are defined.
BeanReplicator.newBeanReplicatable(customTransformer()).replicateBean(bean);
private static BeanTransformerSpi customTransformer() {
BeanTransformerSpi beanTransformer = BeanTransformer.newBeanTransformer();
return beanTransformer.initBeanSourceHandler(new BeanSourceHandler() {
public void handleBeanSource(Object fromBean, Method readerMethod, Object propertyValue) {
System.out.println(
String.valueOf(fromBean.getClass().getSimpleName() + "."
+ readerMethod.getName() + "=" + propertyValue));
}
});
}