java 通过反射获取对象中list属性值

时间:2024-10-14 18:25:58
package com.lubang.test; import com.alibaba.fastjson.JSON; import com.study.reflex.*; import org.junit.Test; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ReflexTest { @Test public void reflexTest() throws Exception { WomenResponse womenResponse = buildSource(); BaseResult<BaseResponse> sourceResult = new BaseResult<>(); sourceResult.setCode(200); sourceResult.setSuccess(true); sourceResult.setData(womenResponse); System.out.println("source:"+JSON.toJSONString(sourceResult)); //将ReflexResponse中list中的对象值赋值给TargeResponse BaseResult<TargeResponse> tar = buildTargeByReflex(sourceResult,Women.class); System.out.println("targe:"+ JSON.toJSONString(tar)); } //这里使用泛型适用性更广 private <T,R> BaseResult<TargeResponse> buildTargeByReflex(BaseResult<T> baseResult, Class<R> targeClass) throws Exception { TargeResponse targeResponse = new TargeResponse(); if(null != baseResult){ List<User> list = new ArrayList<>(); //获取baseResult中data数据即:BaseResponse T data = baseResult.getData(); Class<?> aClass = data.getClass(); //BaseResponse中items属性 Field items = aClass.getDeclaredField("items"); items.setAccessible(true); Object obj = items.get(data); //将object转成list List<R> tarList = objCastList(obj,targeClass); //遍历list for (R r : tarList) { Class<?> rClass = r.getClass(); Field[] rFileds = rClass.getDeclaredFields(); //new 一个目标对象 User user = new User(); Class<? extends User> userClass = user.getClass(); //取目标对象所有属性名称 List<String> userFiledNames = Arrays.stream(userClass.getDeclaredFields()).map(f -> f.getName()).collect(Collectors.toList()); for (Field rFiled : rFileds) { //取值 rFiled.setAccessible(true); String name = rFiled.getName(); Object vaule = rFiled.get(r); //赋值 if(userFiledNames.contains(name)){ Field targeField = userClass.getDeclaredField(name); targeField.setAccessible(true); targeField.set(user,vaule); } } list.add(user); } targeResponse.setItmes(list); } BaseResult<TargeResponse> result = new BaseResult<>(); result.setData(targeResponse); return result; } private <R> List<R> objCastList(Object obj, Class<R> clazz) { List<R> list = new ArrayList<>(); if(obj instanceof List<?>){ for (Object o :(List<?>)obj){ list.add(clazz.cast(o)); } } return list; } private WomenResponse buildSource() { Women women = new Women(1,"zhangsan","北海道"); List<Women> list = new ArrayList<>(); list.add(women); WomenResponse source = new WomenResponse(); source.setItems(list); return source; } }

相关文章