1、工具类如下:
package com.merit.performancemonitoring.util;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
@Slf4j
public class BeanCopyUtil {
public static <T> void merge(T origin, T destination) {
if (origin == null || destination == null) {
return;
}
if (!origin.getClass().equals(destination.getClass())) {
return;
}
Field[] fields = origin.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Object value = field.get(origin);
if (null != value) {
field.set(destination, value);
}
} catch (IllegalAccessException e) {
log.error("访问对象异常", e);
}
field.setAccessible(false);
}
}
}
2、具体实例:
private List<RdsPerformanceEntity> makeupData(DescribeDBInstancePerformanceResponse response) {
Map<String, String> maps = rdsConfig.getDbInstanceIpMaps();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
List<RdsPerformanceEntity> rdsList = new ArrayList<>();
RdsPerformanceEntity rds = RdsPerformanceEntity.builder()
.requestId(response.getRequestId())
.dBInstanceId(response.getDBInstanceId())
.engine(response.getEngine())
.startTime(response.getStartTime())
.endTime(response.getEndTime())
.build();
for (DescribeDBInstancePerformanceResponse.PerformanceKey performanceKey : response.getPerformanceKeys()) {
RdsPerformanceEntity rdsKey = RdsPerformanceEntity.builder().build();
BeanCopyUtil.merge(rds, rdsKey);
rdsKey.setKey(performanceKey.getKey());
rdsKey.setUnit(performanceKey.getUnit());
rdsKey.setValueFormat(performanceKey.getValueFormat());
for (DescribeDBInstancePerformanceResponse.PerformanceKey.PerformanceValue pValue : performanceKey.getValues()) {
RdsPerformanceEntity rdsValue = RdsPerformanceEntity.builder().build();
BeanCopyUtil.merge(rdsKey, rdsValue);
rdsValue.setValue(pValue.getValue());
rdsValue.setDate(pValue.getDate());
Date date = new Date();
rdsValue.setCreateTime(df.format(date));
String hostIp = maps.get(rdsValue.getDBInstanceId());
if (hostIp == null) {
hostIp = "null";
}
rdsValue.setHostIp(hostIp);
rdsValue.setId(sdf.format(date) + hostIp);
rdsList.add(rdsValue);
}
}
return rdsList;
}