web123456

java Getting the value of a list property in an object via reflection

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)); // Assign the value of the object in the list in ReflexResponse to TargeResponse. BaseResult<TargeResponse> tar = buildTargeByReflex(sourceResult,Women.class); System.out.println("targe:"+ JSON.toJSONString(tar)); } // Use generalization here for wider applicability. 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<>(); //get data in baseResult i.e.:BaseResponse T data = baseResult.getData(); Class<?> aClass = data.getClass(); //items property in BaseResponse Field items = aClass.getDeclaredField("items"); items.setAccessible(true); Object obj = items.get(data); //convert object to list List<R> tarList = objCastList(obj,targeClass); //Iterate through the list for (R r : tarList) { Class<?> rClass = r.getClass(); Field[] rFileds = rClass.getDeclaredFields(); //new a target object User user = new User(); Class<? extends User> userClass = user.getClass(); //Take the names of all attributes of the target object List<String> userFiledNames = Arrays.stream(userClass.getDeclaredFields()).map(f -> f.getName()).collect(Collectors.toList()); for (Field rFiled : rFileds) { //Taking values rFiled.setAccessible(true); String name = rFiled.getName(); Object vaule = rFiled.get(r); //assignment 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","Hokkaido"); List<Women> list = new ArrayList<>(); list.add(women); WomenResponse source = new WomenResponse(); source.setItems(list); return source; } }