gpt4 book ai didi

Java toString - ToStringBuilder 不够;不会穿越

转载 作者:IT老高 更新时间:2023-10-28 21:17:28 25 4
gpt4 key购买 nike

我需要能够遍历我的整个对象图并记录所有成员字段的所有内容。

例如:对象 A 具有对象 B 的集合,对象 B 具有对象 C 的集合,并且 A、B、C 上有附加字段,等等。

Apache Commons ToStringBuilder是不够的,因为它不会遍历对象图或集合的输出内容。

有没有人知道另一个库可以做到这一点或有一个代码片段可以做到这一点?

最佳答案

您可以使用 org.apache.commons.lang.builder.ReflectionToStringBuilder 遍历整个树。诀窍是在 ToStringStyle 你需要遍历值。 ToStringStyle 将处理已处理的值,并且不允许递归。我们开始:

System.out.println(ReflectionToStringBuilder.toString(schema, new RecursiveToStringStyle(5)));

private static class RecursiveToStringStyle extends ToStringStyle {

private static final int INFINITE_DEPTH = -1;

/**
* Setting {@link #maxDepth} to 0 will have the same effect as using original {@link #ToStringStyle}: it will
* print all 1st level values without traversing into them. Setting to 1 will traverse up to 2nd level and so
* on.
*/
private int maxDepth;

private int depth;

public RecursiveToStringStyle() {
this(INFINITE_DEPTH);
}

public RecursiveToStringStyle(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--;
}
}

// another helpful method
@Override
protected void appendDetail(StringBuffer buffer, String fieldName, Collection<?> coll) {
depth++;
buffer.append(ReflectionToStringBuilder.toString(coll.toArray(), this, true, true));
depth--;
}
}

关于Java toString - ToStringBuilder 不够;不会穿越,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3149951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com