Java-反射-反射设置父类字段的值-获取包括父类的所有字段
getField和getDeclaredField的区别:
这两个方法都是用于获取字段
getField 只能获取public的,包括从父类继承来的字段。
getDeclaredField 可以获取本类所有的字段,包括private的,但是不能获取继承来的字段。 (注: 这里只能获取到private的字段,但并不能访问该private字段的值,除非加上setAccessible(true))
//使用示例
private void setDayXdangrifeishuipaifang(FoulWaterSlaveWith28DayVo foulWaterSlaveWithAllDayVo, Integer dayNumber, Integer dangrifeishuipaifang) {
String fieldName = "day" + dayNumber + "dangrifeishuipaifang";
Field field = getFieldIncludeSuper(foulWaterSlaveWithAllDayVo.getClass(), fieldName);
// Field field = null;
// try {
// field = foulWaterSlaveWithAllDayVo.getClass().getDeclaredField(fieldName);
// } catch (NoSuchFieldException e) {
// log.error("设置当日废水排放量出现异常:{}", e);
// }
// if (field == null) {
// return;
// }
// Field[] fields = foulWaterSlaveWithAllDayVo.getClass().getDeclaredFields();
// for (Field field : fields) {
//day1dangrifeishuipaifang
boolean isTargetField = field.getName().equals("day" + dayNumber + "dangrifeishuipaifang");
if (isTargetField) {
try {
field.setAccessible(true);
// if (clearField) {
// //好像做不到,定义4个类
// } else {
field.set(foulWaterSlaveWithAllDayVo, dangrifeishuipaifang);
// }
} catch (IllegalAccessException e) {
log.error("设置当日废水排放量出现异常:{}", e);
}
}
// }
}
//https://blog.csdn.net/hkl_Forever/article/details/120557672
//获取所有的字段,包括父类
public static Field[] getAllFields(Class<?> clazz) {
List<Field> fieldList = new ArrayList<>();
while (clazz != null) {
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
clazz = clazz.getSuperclass();
}
Field[] fields = new Field[fieldList.size()];
return fieldList.toArray(fields);
}
//获取父类中的字段
public static Field getFieldIncludeSuper(Class<?> clazz, String fieldName) {
Field field = null;
while (clazz != null) {
try {
field = clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException ignore) {
// log.error("获取字段失败:fieldName{},异常:{}", fieldName, ignore);
}
if (field == null) {
clazz = clazz.getSuperclass();
} else {
break;
}
}
return field;
}
正文到此结束