fix:修复了代码逻辑中子类参数不能获取父类字段的问题

main
wb2476 2026-04-27 16:48:44 +08:00
parent aeac8ea23f
commit 74c8e7704e
1 changed files with 14 additions and 6 deletions

View File

@ -11,14 +11,22 @@ public class ObjReflect {
} }
public static Object getValue(Object obj, String fieldName) { public static Object getValue(Object obj, String fieldName) {
Class<?> clazz = obj.getClass();
while (clazz != null) {
try { try {
Field field = obj.getClass().getDeclaredField(fieldName); Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true); field.setAccessible(true);
return field.get(obj); return field.get(obj);
} catch (NoSuchFieldException e) {
// 未声明该字段继续向上查父类
clazz = clazz.getSuperclass();
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }
} }
// 整个链路没有该字段返回null
return null;
}
public static String getValueAsString(Object obj, String fieldName) { public static String getValueAsString(Object obj, String fieldName) {
Object value = getValue(obj, fieldName); Object value = getValue(obj, fieldName);