Java 递归遍历对象属性:示例代码及详解
下面是一个递归遍历 Java 对象属性的示例代码:
public class PropertyUtils {
public static void printProperties(Object obj) {
if (obj == null) {
return;
}
Class<?> clazz = obj.getClass();
System.out.println('Properties of ' + clazz.getName() + ':');
for (Field field : clazz.getDeclaredFields()) {
try {
field.setAccessible(true);
Object value = field.get(obj);
System.out.println(field.getName() + ' = ' + value);
printProperties(value);
} catch (IllegalAccessException e) {
System.err.println('Error accessing field: ' + field.getName() + ' in class ' + clazz.getName());
}
}
}
}
这个工具类的 printProperties 方法接收一个对象作为参数,并遍历它的所有属性,打印出属性名和值。如果属性的值也是一个对象,则递归调用 printProperties 方法,继续遍历内部对象的属性。需要注意的是,为了能够访问对象的私有属性,需要调用 field.setAccessible(true)。
原文地址: https://www.cveoy.top/t/topic/otpI 著作权归作者所有。请勿转载和采集!