为了观察变量方便,我们通常会重写实体类模型的toString方法,可是每一个类都写。有些冗余。
事实上,能够这样子:
package others;
import java.io.Serializable;
import java.lang.reflect.Field;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* 重写toString()的实体类基类
* @author limenghua
*
*/
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 4861363281663993175L;
/**
* toString
* 打印演示样例:synchronizedtest.Account@768965fb[name=张三, ,amount=500.0, ]
*/
@Override
public String toString() {
ToStringBuilder builder = new ToStringBuilder(this);
Field[] fields = this.getClass().getDeclaredFields();
try {
for (Field f : fields) {
f.setAccessible(true);
builder.append(f.getName(), f.get(this)).append("\n");
}
} catch (Exception e) { // Suppress
builder.append("toString builder encounter an error");
}
return builder.toString();
}
}实体类继承这个类就可以:
public class Account extends BaseModel{……}
或者,我们能够用一种更加简单的方式写基类:
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
/**
* 重写toString()的实体类基类
*
* @author limenghua
*/
public class BaseModel implements Serializable {
private static final long serialVersionUID = 4861363281663993175L;
/**
* toString
* 打印演示样例:Account@768965fb[
* name=张三
* amount=500.0
* ]
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this,
ToStringStyle.MULTI_LINE_STYLE);
}
}
打印效果: