迭代没有args和非void返回类型的Java对象方法并打印toString返回值(用于调试)

时间:2017-05-27 16:37:32

标签: java debugging reflection dump

我想转储复杂Java对象的内容以进行调试。

例如,我想从toString()对象的所有get...()方法的返回值转储HttpServletRequest

我对字段不感兴趣,而是对方法返回值感兴趣。

我不确定是否可以使用commons-beanutilsReflectionToStringBuilder.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();
}

但我想使用标准和灵活的东西......

0 个答案:

没有答案