public String toString() {
String str = this.getClass().getName() + " >>> "; // 获取类名
Field[] field = this.getClass().getDeclaredFields();
for (int i = 0; i < field.length; ++i) {
try {
Field f = field[i];
String fieldName = f.getName();
String getName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1); // get方法的名字
Class classType = this.getClass();
Method getMethod = classType.getMethod(getName, new Class[] {});
Object value = getMethod.invoke(this, new Object[] {});
str += fieldName + ": " + value + ",";
} catch (Exception e) {
// e.printStackTrace();
}
}
return str;
}java反射toString
最新推荐文章于 2025-08-18 11:30:24 发布
本文介绍如何使用Java实现将对象转换为字符串的功能,包括获取类名、遍历类中所有属性并封装成字符串的过程。通过实例演示,帮助开发者掌握对象转字符串的技巧。

3万+

被折叠的 条评论
为什么被折叠?



