- 1、传入任意 List 对象数据,有Id,但没有用户姓名
- 2、通过反射获取 List 中的 Ids
- 3、通过 Ids 批量查询数据,获取用户姓名
- 4、填充 List 对象中的姓名值
- 使用示例: insertMchUserInfoData(userVos, "id", "fullName")
代码示例
publicvoid insertMchUserInfoData(List data, String idKey, String nameKey) { try { // 循环获取指定 属性key 的值 List ids = new ArrayList<>(); for (T t : data) { // 获取类字段 Class> classIs = t.getClass(); Field fieId = this.getField(classIs, idKey); if (fieId == null) { continue; } // 获取类字段值 fieId.setAccessible(true); Object id = fieId.get(t); if (id != null) { ids.add(Long.parseLong(id.toString())); } } // 可以提供 Ids 批量查询相关数据, 在修改是获取数据对 原数据指定 属性key 的值进行数据填充或替换 // 如果查询返回的 list 可以分组为 Map , 便于设置值获取数据 // 循环修改指定 属性key 的值 for (T t : data) { Class> classIs = t.getClass(); // 修改指定 key 的值 if (nameKey != null) { Field nameFieId = this.getField(classIs, nameKey); if (nameFieId != null) { nameFieId.setAccessible(true); nameFieId.set(t, "修改后的值, 使用Ids 查询的值进行填充"); } } } } catch (IllegalAccessException e) { e.printStackTrace(); } } private Field getField(Class> classIs, String fieldKey) { Field fieId = null; // 先找当前类 try { fieId = classIs.getDeclaredField(fieldKey); } catch (NoSuchFieldException e) { //e.printStackTrace(); } // 当前类没有找父类 if (fieId == null) { try { fieId = classIs.getSuperclass().getDeclaredField(fieldKey); } catch (NoSuchFieldException e) { // e.printStackTrace(); } } return fieId; }



