根据属性名获取对象值
public static Object getPropertyValue(Object object, String fieldName) {
try {
Field field = getFieldByClasss(fieldName, object);
field.setAccessible(true);
return Optional.ofNullable(field.get(object)).orElse("-");
} catch (Exception e) {
logger.debug(e.getMessage(), e);
return "-";
}
}
private static Field getFieldByClasss(String fieldName, Object object) {
Field field = null;
for (Class clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
field = clazz.getDeclaredField(fieldName);
} catch (Exception e) {
logger.debug(e.getMessage(), e);
}
}
return field;
}
![用法](https://i-blog.csdnimg.cn/blog_migrate/a28543f0d1467d426dc96dda5f1b418d.png#pic_center)