2 回答
TA贡献1853条经验 获得超6个赞
我已经在我的机器上尝试过代码,它应该适用于你的例子。
class MyToStringStyle extends ToStringStyle {
public MyToStringStyle() {
setFieldSeparator(" ");
setUseFieldNames(false);
setUseIdentityHashCode(false);
setUseClassName(false);
setContentStart("");
setContentEnd("");
}
@Override
protected void appendDetail(StringBuffer buffer, String fieldName, Collection<?> coll) {
if (coll.isEmpty()) return;
Iterator iter = coll.iterator();
buffer.append(iter.next());
while (iter.hasNext()) {
buffer.append(" ").append(iter.next());
}
}
}
TA贡献1859条经验 获得超6个赞
我决定编辑代码,因为我已经构建了一个自定义的 ReflectionToStringBuilder 方法。这是方法:
public static String toString(Object object) {
Class<?> clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
StringBuilder stringBuilder = new StringBuilder();
for (Field field : fields) {
try {
field.setAccessible(true);
Object value = field.get(object);
// check if the value is actually a list
if (List.class.isAssignableFrom(value.getClass())) {
// this for some reason gives the unchecked cast warning, but we actually are
// checking it so don't worry!
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) value;
for (Object element : list) {
stringBuilder.append(element.toString()).append(" ");
}
} else if (value.getClass().isArray()) {
Object[] array = (Object[]) value;
for (Object element : array) {
stringBuilder.append(element.toString()).append(" ");
}
} else {
stringBuilder.append(value.toString()).append(" ");
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
我已经对其进行了测试,并且效果很好。
我的课:
int x = 0;
String string = "string0";
List<String> stringList = Arrays.asList("string1");
String[] stringArray = {"string3", "string4"};
public static void main(String[] args) {
Test test = new Test();
System.out.println(toString(test));
}
输出:
0 string0 string1 string3 string4
添加回答
举报