I would like to dump content of complex Java objects for debugging purpose.
For example I want to dump of toString()
from return value of all get...()
methods of HttpServletRequest
object.
I am not interested in fields but rather in methods return values.
I am not sure if it's possible with commons-beanutils
or ReflectionToStringBuilder.toString()
Currently I implemented with Introspector
core API:
public static String dump(Object obj, String regex) {
StringBuilder sb = new StringBuilder();
try {
BeanInfo info = Introspector.getBeanInfo(obj.getClass());
for (MethodDescriptor descr : info.getMethodDescriptors()) {
String name = descr.getName();
Method method = descr.getMethod();
if ( ! name.matches(regex))
continue;
if (method.getParameterCount() > 0)
continue;
if (Stream.class.isAssignableFrom(method.getReturnType()))
continue;
Object objValue = method.invoke(obj);
String strValue = Optional.ofNullable(objValue).map(Object::toString).orElse("null");
logger.info("name: {}, value: {}", name, strValue);
sb.append(name);
sb.append(" => ");
sb.append(strValue);
sb.append("\n");
}
} catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
ex.printStackTrace();
}
return sb.toString();
}
but I would like to use something standard and flexible...
Aucun commentaire:
Enregistrer un commentaire