Java toString - ToStringBuilder not sufficient; won't traverse

前端 未结 7 1876
Happy的楠姐
Happy的楠姐 2020-12-07 23:18

I need to be able to traverse through my entire object graph and log all contents of all member fields.

For example: Object A has a collection of Object B\'s which

7条回答
  •  时光取名叫无心
    2020-12-07 23:31

    This is something I've written for my personal use. Let me know if it helps:

    public static String arrayToString(final Object obj){
        if (obj == null) {
            return "";
        }
        else {
            Object array = null;
            if (obj instanceof Collection) {
                array = ((Collection) obj).toArray();
            }
            else if (obj.getClass().isArray()) {
                array = obj;
            }
            else {
                return notNull(obj);
            }
            int length = Array.getLength(array);
            int lastItem = length - 1;
            StringBuffer sb = new StringBuffer("[");
            for (int i = 0; i < length; i++) {
                sb.append(arrayToString(Array.get(array, i)));
                if (i < lastItem) {
                    sb.append(", ");
                }
            }
            sb.append(']');
            return sb.toString();
        }
    }
    

提交回复
热议问题