JavaBeanをHashMap#toString()っぽく表示

いちいちBeanUtilsを使いたくないので。
Beanの親クラスのtoString()に仕込んでおくと便利かも。


private String bean2string(Object bean) throws IntrospectionException,
IllegalAccessException, InvocationTargetException,
InvocationTargetException {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
StringBuffer buf = new StringBuffer("{");

for (int i = 0; i < props.length; i++) {
String name = props[i].getName();

if ("class".equals(name)) {
continue;
}

Method readMethod = props[i].getReadMethod();

if (readMethod == null) {
continue;
}

Object value = readMethod.invoke(bean, new Class[0]);
buf.append(name + "=" + value);

if (i < props.length - 1) {
buf.append(", ");
}
}

buf.append("}");
return buf.toString();
}