原Bean: source
目标Bean: target
如果copy的话需要注意
1、同属性之间类的复制,我这里source的String对应到target为List<Map<String,Object>>>的话,做了特殊处理
2、场景是原Bean的字段少于目标Bean的字段
private String firstSettleType;
private String lastSettleType;
private int firstSettleDate;
private int lastSettleDate;
private BigDecimal orderAmount;
private String currency;
private String remark;
private String pledgeBonds; //json串
转为
private String lastSettleType;
private int firstSettleDate;
private int lastSettleDate;
private BigDecimal orderAmount;
private String currency;
private String remark;
private List<Map<String,Object>> pledgeBonds;
package com.hundsun.cj.util;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hundsun.cj.command.BankOutrightIssueCommand;
import com.hundsun.cj.command.ExchangeRepoIssueCommand;
import com.hundsun.cj.command.PrimaryOrderIssueCommand;
import com.hundsun.cj.common.CommonException;
import com.hundsun.cj.domain.request.BankOutrightIssueRequest;
import com.hundsun.cj.domain.request.ExchangeRepoIssueRequest;
import com.hundsun.cj.domain.request.PrimaryOrderIssueRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.function.DoubleToIntFunction;
/**
* bean相关的工具类
* @author luzh32717
* @date 2020/10/14 9:36
* @version 1.0
*/
public class MyBeanUtil {
/**
* 复制属性相同的两个类, 前提是两个类都重载了setter/getter方法
* @param source 源类
* @param target 目标类
* @return T 目标类型
* @throws CommonException 公共异常
*/
public static<T> T copy(Object source,T target) throws CommonException {
if(source == null || target == null){
throw new CommonException("-1","同属性bean复制时入参不能为空!");
}
Field[] declaredFields = source.getClass().getDeclaredFields();
Class<?> targetClass = target.getClass();
if(declaredFields.length <= 0 || declaredFields.length > targetClass.getDeclaredFields().length){
throw new CommonException("-1","同属性bean复制时入参违法!");
}
for(Field declaredField : declaredFields){
declaredField.setAccessible(true);
Field targetField = null;
try {
targetField = targetClass.getDeclaredField(declaredField.getName());
targetField.setAccessible(true);
if(targetField.getType().equals(declaredField.getType())){
targetField.set(target,declaredField.get(source));
}//当存在Request为String但Command中类型为List的相同名称的字段
else if(targetField.getType().toString().contains("java.util.List") && declaredField.getType().toString().contains("java.lang.String")){
targetField.set(target,jsonToObjectList((String) declaredField.get(source)));
}else{
throw new CommonException("-1","同属性bean复制时存在名称相同但类型不同的字段");
}
} catch (NoSuchFieldException e) {
LOGGER.debug(declaredField.getName()+"没找到");
} catch (IllegalAccessException e){
throw new CommonException("-1","同属性bean复制时: " + e.getMessage());
}
}
return target;
}
/**
* 将json串转换为List<Map<String,Object>>>
* @param json json串
* @return List<Map<String,Object>>>
* @throws CommonException 公共类型的异常
*/
public static List<Map<String,Object>> jsonToObjectList(String json) throws CommonException{
List<Map<String,Object>> list = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
list = objectMapper.readValue(json, new TypeReference<List<Map<String,Object>>>(){});
} catch (IOException e) {
throw new CommonException("-1","String字段转List<Map<String,Object>>>字段异常: " + e.getMessage());
}
return list;
}
public static void main(String[] args) throws CommonException {
PrimaryOrderIssueRequest primaryOrderIssueRequest = new PrimaryOrderIssueRequest();
primaryOrderIssueRequest.setCombNo("1");
primaryOrderIssueRequest.setOrderPrices("[{\"price\":\"10.12\",\"amount\":\"500000\"},{\"price\":\"10.18\",\"amount\":\"500000\"}]");
PrimaryOrderIssueCommand copy = copy(primaryOrderIssueRequest, new PrimaryOrderIssueCommand());
System.out.println(copy);
System.out.println(copy.getOrderPrices().toString());
}
}
package com.hundsun.cj.common;
import com.hundsun.cj.constant.Errors;
import lombok.Data;
@Data
public class CommonException extends Exception{
private String exceptionCode;
private String exceptionMsg;
public CommonException(){
super();
}
public CommonException(String exceptionMsg){
super(exceptionMsg);
}
public CommonException(String exceptionCode,String exceptionMsg){
this(exceptionMsg);
this.exceptionMsg = exceptionMsg;
this.exceptionCode = exceptionCode;
}
public CommonException(Errors errors){
this(errors.getCode(),errors.getMsg());
}
}
package com.hundsun.cj.constant;
/**
* @author hspcadmin
*/
public enum Errors{
/**
* Http调用异常
*/
ERROR_HTTP_REQUEST("000001", "发送报文失败/解析报文失败"),
ERROR_GET_RES_NULL("000002", "发送Get的Http请求异常.response为空"),
ERROR_POST_RES_NULL("000002", "发送Post的Http请求异常.response为空"),
ERROR_GET_EXCEPTION("000003", "发送Get请求时发生异常.异常信息:"),
ERROR_POST_EXCEPTION("000004", "发送Post请求时发生异常.异常信息:"),
ERROR_TRANS_EXCEPTION("000005", "数据转换发生异常.异常信息:"),
ERROR_CJHX_AUTH_FAIL("4001", "未经身份认证"),
ERROR_CJHX_NOT_METHOD("4002", "请求方法不支持"),
ERROR_CJHX_NOT_RESOURCE("4004", "请求的资源不存在"),
ERROR_CJHX_NOT_CLIENT("4006", "clientId参数不存在"),
ERROR_CJHX_NOT_SIGN("4008", "signature参数不存在"),
ERROR_CJHX_TIMEOUT("4009", "请求超时"),
ERROR_CJHX_NOT_TIMESTMP("4010", "时间戳参数不存在"),
ERROR_CJHX_SIGN_FAIL("4011", "签名校验失败"),
ERROR_CJHX_SERVICE_FAIL("5000", "服务内部错误"),
ERROR_CJHX_SERVICE_STOP("5001", "接口暂时服务访问,请重试")
;
private String code;
private String msg;
Errors(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return this.code;
}
public String getMsg() {
return this.msg;
}
public static String getMsg(String code) {
for (Errors ele : values()) {
if(ele.getCode().equals(code)) {
return ele.getMsg();
}
}
return "未定义错误信息";
}
}