- Java 将数据库返回的实体类集合其中某一个属性取出封装成List
我的需求:我请求数据库返回了对应实体类的集合,但现在我想获得实体中某一个属性的集合,这个属性要由外部参数决定。
我的解决:如果参数是单一且确定的,stream流直接getXXX即可实现,但现在属性不是确定的,所以就需要通过定义函数实现,
public static Object getPropertyValue(Object obj, String propertyName) { try { Class<?> clazz = obj.getClass(); Field field = clazz.getDeclaredField(propertyName); field.setAccessible(true); return field.get(obj); } catch (Exception e) { e.printStackTrace(); return null; } }
通过这个反射相关的函数,就可以动态的获取对应实体传入参数的属性值
String myproperty = "name" List<MyEntity> myEntityList = HomeDao.querymy(params); entityProperties = myEntityList.stream() .map(entity -> getPropertyValue(entity, myproperty)) .collect(Collectors.toList());
-
Java 将一个实体类的全部属性值封装成list返回
-
我的需求:请求数据库返回了对应实体类的集合,如果直接返回给前端会是map格式数据,但现在我的需要是我请求回来的实体集合只有一个,我想把属性值取出,封装成List
-
我的解决:代码片段
List<Object> propertyValueList = new ArrayList<>(); List<Object> propertyNameList = new ArrayList<>(); List<myEntity> myEntityList = HomeDao.querymy(params); // 获取第一个实体对象 myEntity firstEntity = myEntityList.get(0); // 获得实体的所有字段 Field[] fields = firstEntity.getClass().getDeclaredFields(); // 遍历每个字段并获取属性值 for (Field field : fields) { try { // 设置可访问私有字段 field.setAccessible(true); // 获取字段的属性值 Object propertyValue = field.get(firstEntity); // 添加属性值到列表中 propertyValueList.add(propertyValue); //将每个属性的属性名添加到属性名列表 propertyNameList.add(field.getName()); } catch (Exception e) { e.printStackTrace(); } }
-