我想转储复杂Java对象的内容以进行调试。
例如,我想从toString()
对象的所有get...()
方法的返回值转储HttpServletRequest
。
我对字段不感兴趣,而是对方法返回值感兴趣。
我不确定是否可以使用commons-beanutils
或ReflectionToStringBuilder.toString()
目前我使用Introspector
核心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();
}
但我想使用标准和灵活的东西......