java中object的toString()方法咱使用的也比较频繁,常见的场景如:使用log4j等输出日志对象的时候,会调用对象的toString()方法。而object的toString()方法默认实现如下:
/**
* Returns a string representation of the object. In general, the
* {@code toString} method returns a string that
* "textually represents" this object. The result should
* be a concise but informative representation that is easy for a
* person to read.
* It is recommended that all subclasses override this method.
* <p>
* The {@code toString} method for class {@code Object}
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `{@code @}', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
因此,咱通常会在对象中重写对象的toString()方法,比如得到一个json串之类的,如下:
/**
* @author ying.pan
* @date 2019/9/16 11:41 AM.
*/
public class MoreObj implements Serializable {
/**
* test value
*/
private String value;
/**
* test text
*/
private String text;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return reflectionToString(this, JSON_STYLE);
}
}
MoreObjects对象提供了toStringHelper()方法,使我们可以更加便捷的实现指定的toString()方法,大致用法如下:
private static void testMoreObjectsToString() {
MoreObj moreObj = new MoreObj();
moreObj.setText("text");
moreObj.setValue("value");
//step1 测试输出默认object toString方法
System.out.println("重写toString(),返回json格式: "+moreObj.toString());
//step2 测试toStringHelper(),传入.class
//第一个 params为key,第二个params为 value
System.out.println("使用toStringHelper(),clazz: "+MoreObjects.toStringHelper(MoreObj.class).add(moreObj.getValue(), "test value")
.add(moreObj.getValue(), "test value").toString());
//step3 测试toStringHelper(),传入self Obj
//第一个 params为key,第二个params为 value
System.out.println("使用toStringHelper(),self object: "+MoreObjects.toStringHelper(moreObj).add(moreObj.getValue(), "test value")
.add(moreObj.getValue(), "test value").toString());
}
输出结果:

image.png
值得一说的是: MoreObjects.toStringHelper(xx).add(key,value)支持重复的(k,v);
toStringHelper的时候会返回一个ToStringHelper,至于里面包含的内容以及最终MoreObjects的toString()的具体实现,感兴趣的小伙伴可以自己去发现哦,也许能看见一些有趣的事情.......
网友评论