Java toString - ToStringBuilder not sufficient; won't traverse

前端 未结 7 1873
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条回答
  •  -上瘾入骨i
    2020-12-07 23:36

    Extended above code for List and Map:

    Code :

    public class MultipleRecursiveToStringStyle extends ToStringStyle {
    private static final int    INFINITE_DEPTH  = -1;
    
    private int                 maxDepth;
    
    private int                 depth;
    
    public MultipleRecursiveToStringStyle() {
        this(INFINITE_DEPTH);
    }
    
    public MultipleRecursiveToStringStyle(int maxDepth) {
        setUseShortClassName(true);
        setUseIdentityHashCode(false);
    
        this.maxDepth = maxDepth;
    }
    
    @Override
    protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
        if (value.getClass().getName().startsWith("java.lang.")
                || (maxDepth != INFINITE_DEPTH && depth >= maxDepth)) {
            buffer.append(value);
        } else {
            depth++;
            buffer.append(ReflectionToStringBuilder.toString(value, this));
            depth--;
        }
    }
    
    @Override
    protected void appendDetail(StringBuffer buffer, String fieldName, Collection coll) {
        Collections.sort((List) coll);
        for(Object value: coll){
            if (value.getClass().getName().startsWith("java.lang.")
                    || (maxDepth != INFINITE_DEPTH && depth >= maxDepth)) {
                buffer.append(value);
            } else {
                depth++;
                buffer.append(ReflectionToStringBuilder.toString(value, this));
                depth--;
            }
        }
    }
    
    @Override
    protected void appendDetail(StringBuffer buffer, String fieldName, Map map) {
        TreeMap sortedMap = new TreeMap(map);
        for(Map.Entry kvEntry: sortedMap.entrySet()){
            Object value = kvEntry.getKey();
            if (value.getClass().getName().startsWith("java.lang.")
                    || (maxDepth != INFINITE_DEPTH && depth >= maxDepth)) {
                buffer.append(value);
            } else {
                depth++;
                buffer.append(ReflectionToStringBuilder.toString(value, this));
                depth--;
            }
            value = kvEntry.getValue();
            if (value.getClass().getName().startsWith("java.lang.")
                    || (maxDepth != INFINITE_DEPTH && depth >= maxDepth)) {
                buffer.append(value);
            } else {
                depth++;
                buffer.append(ReflectionToStringBuilder.toString(value, this));
                depth--;
            }
        }
    }}
    

提交回复
热议问题