Car*_*eon 5 java tostring apache-commons utility-method
是否有来自Apache Commons的toString实用程序,它只会在结果的toString值中包含那些非null的字段?
例如:
public class Person {
String name;
String height;
String age;
}
Run Code Online (Sandbox Code Playgroud)
并创建一个具有名称和年龄的实例.然后调用该实用程序,例如:
utility.toStringNonNull(person);
Run Code Online (Sandbox Code Playgroud)
将输出:
[姓名=玛丽,年龄= 28]
Car*_*eon 11
我能够通过扩展Apache的ToStringStyle类来做到这一点:
public static class TestStyle extends ToStringStyle{
TestStyle() {//constructor is copied from ToStringStyle.MULTI_LINE_STYLE
super();
this.setContentStart("[");
this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + " ");
this.setFieldSeparatorAtStart(true);
this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]");
}
//override this to do checking of null, so only non-nulls are printed out in toString
@Override
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
if (value != null) {
super.append(buffer, fieldName, value, fullDetail);
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用是这样的:
public static void main(String[] args) {
Person p = new Person();
p.setName("Tester");
ToStringStyle style = new TestStyle();
System.out.println("toString = " + ToStringBuilder.reflectionToString(p, style));
}
Run Code Online (Sandbox Code Playgroud)
这将导致:Person @ 37403a09 [name = Tester]
| 归档时间: |
|
| 查看次数: |
5380 次 |
| 最近记录: |