欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

toString 方法

程序员文章站 2022-06-16 22:53:53
...

@Override
public String toString() {
StringBuilder buf = new StringBuilder();
Method[] methods = this.getClass().getMethods();
boolean isFirst = true;
for (int i = 0, n = methods.length; i < n; i++) {
try {
Method method = methods[i];
if ((method.getModifiers() & Modifier.PUBLIC) == 1
&& method.getDeclaringClass() != Object.class
&& (method.getParameterTypes() == null || method
.getParameterTypes().length == 0)) {
String methodName = method.getName();
String property = null;
if (methodName.startsWith("get")) {
property = methodName.substring(3, 4).toLowerCase()
+ methodName.substring(4);
} else if (methodName.startsWith("is")) {
property = methodName.substring(2, 3).toLowerCase()
+ methodName.substring(3);
}
if (property != null) {
Object value = method.invoke(this, new Object[0]);
if (isFirst)
isFirst = false;
else
buf.append(",");
buf.append(property);
buf.append(":");
if (value instanceof String)
buf.append("\"");
buf.append(value);
if (value instanceof String)
buf.append("\"");
}
}
} catch (Exception e) {
// ignore
}
}
return "{" + buf.toString() + "}";
}