public class ObjectUtils {
private static final String LINE = System.getProperty("line.separator");
static class Car{
private String id;
private String name;
private Date creatTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreatTime() {
return creatTime;
}
public void setCreatTime(Date creatTime) {
this.creatTime = creatTime;
}
}
public static void main(String[] args) {
Car po = new Car();
po.setId("1");
po.setName("a");
po.setCreatTime(new Date());
System.out.println(ObjectUtils.getToStringFormat(po));
System.out.println(ObjectUtils.getToString(po));
}
public static String getToStringFormat(Object o) {
Class<? extends Object> clazz = o.getClass();
StringBuilder builder =
new StringBuilder()
.append(clazz.toString().substring(clazz.toString().lastIndexOf('.') + 1))
.append(LINE)
.append(" [");
Field[] fields = clazz.getDeclaredFields();
for (int i = fields.length - 1; i >= 0; i--) {
Field field = fields[i];
field.setAccessible(true);
if (i == 0) {
Object fieldValue = getFieldValue(o, field);
builder.append(LINE)
.append(" ")
.append(field.getName())
.append(" = ");
if (fieldValue == null) {
builder.append("null");
} else {
builder.append(fieldValue.toString());
}
builder.append(LINE)
.append(" ]");
} else {
builder.append(LINE)
.append(" ")
.append(field.getName())
.append(" = ");
Object fieldValue = getFieldValue(o, field);
if (fieldValue == null) {
builder.append("null");
} else {
builder.append(fieldValue.toString());
}
builder.append(",");
}
}
return builder.toString();
}
public static String getToString(Object o) {
Class<? extends Object> clazz = o.getClass();
StringBuilder builder =
new StringBuilder()
.append(clazz.toString().substring(clazz.toString().lastIndexOf('.') + 1))
.append(" [");
Field[] fields = clazz.getDeclaredFields();
for (int i = fields.length - 1; i >= 0; i--) {
Field field = fields[i];
field.setAccessible(true);
if (i == 0) {
Object fieldValue = getFieldValue(o, field);
builder.append(field.getName())
.append(" = ");
if (fieldValue == null) {
builder.append("null");
} else {
builder.append(fieldValue.toString());
}
builder.append("]");
} else {
builder.append(field.getName())
.append(" = ");
Object fieldValue = getFieldValue(o, field);
if (fieldValue == null) {
builder.append("null");
} else {
builder.append(fieldValue.toString());
}
builder.append(",");
}
}
return builder.toString();
}
private static Object getFieldValue(Object o,Field field) {
try {
return field.get(o);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
执行结果:
ObjectUtils$Car
[
creatTime = Wed Oct 31 22:29:49 CST 2018,
name = a,
id = 1
]
ObjectUtils$Car [creatTime = Wed Oct 31 22:29:49 CST 2018,name = a,id = 1]