1.原值对象
@Getter @Setter @ToString public class UserDTO implements Serializable { /** * 用户id */ private Integer userId; /** * 用户姓名 */ private String firstName; /** * 用户手机号 */ private String mobile; }
2.赋值接受对象
@Getter @Setter @ToString public class PaymentsRollDO implements Serializable{ /** * 业务ID */ @ApiModelProperty("业绩id") @NotNull private Integer id; /** * 销售ID */ private Integer selUserId; /** * 销售手机号 */ private String sellerMobile; /** * 销售姓名 */ private String sellerName; }
3.转换工具类
public final class UserConvertUtil { /** * Desc: * 反射赋值 * @author wei9.wang * @date 2020/3/14 19:12 **/ static <T> void deal(List<UserDTO> users, List<T> list, String id, String firstName, String mobile){ if(CollectionUtils.isEmpty(list)){ return; } Field[] declaredFields = list.get(0).getClass().getDeclaredFields(); Field userIdField = null; Field mobileField = null; Field firstNameField = null; for (Field field : declaredFields) { String fieldName = field.getName(); if (fieldName.equals(id)) { userIdField = field; userIdField.setAccessible(true); }else if (fieldName.equals(firstName)) { firstNameField = field; firstNameField.setAccessible(true); }else if (fieldName.equals(mobile)) { mobileField = field; mobileField.setAccessible(true); } } if(userIdField == null){ throw new RuntimeException("用户id字段不能为null"); } try { for (T t : list) { Integer userId = (Integer) userIdField.get(t); for (UserDTO user : users) { if(user.getUserId().equals(userId)){ if(mobileField != null){ mobileField.set(t, user.getMobile()); } if(firstNameField != null){ firstNameField.set(t, user.getFirstName()); } } } } } catch (IllegalAccessException e) { e.printStackTrace(); } } }
4.Test测试类
import com.zhangmen.sale.score.feign.dto.UserDTO; import com.zhangmen.sale.score.service.impl.entity.PaymentsRollDO; import java.util.ArrayList; import java.util.List; /** *@ClassName Test *@Description *@Author wangwei *@Date 2020/3/14 18:06 *@Version V1.0 **/ public class Test { public static void main(String[] args) { List<UserDTO> users = new ArrayList<>(); UserDTO u1 = new UserDTO(); u1.setUserId(1); u1.setFirstName("王未"); u1.setMobile("18222255422"); UserDTO u2 = new UserDTO(); u2.setUserId(2); u2.setFirstName("星星"); u2.setMobile("15236265722"); UserDTO u3 = new UserDTO(); u3.setUserId(3); u3.setFirstName("月亮"); u3.setMobile("15236265786"); users.add(u1); users.add(u2); users.add(u3); List<PaymentsRollDO> paymentsRollDOS = new ArrayList<>(); PaymentsRollDO p1 = new PaymentsRollDO(); p1.setSelUserId(1); /*p1.setSellerName(); p1.setSellerMobile();*/ PaymentsRollDO p2 = new PaymentsRollDO(); p2.setSelUserId(2); PaymentsRollDO p3 = new PaymentsRollDO(); p3.setSelUserId(3); paymentsRollDOS.add(p1); paymentsRollDOS.add(p2); paymentsRollDOS.add(p3); UserConvertUtil.deal(users, paymentsRollDOS,"selUserId","sellerName","sellerMobile"); for (PaymentsRollDO p : paymentsRollDOS) { System.out.println(p.getSelUserId()+"|"+p.getSellerName()+"|"+p.getSellerMobile()+"|"); } } }
输出结果: