业务背景:
在工作经常出现俩个List 对象 按照业务需要将不同参数根据规则合并成一个List 所以写了一个简单的工具类。
技术:利用反射
package com.lxs.suanfa.test0914;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @description ComparisonUnitl
* @date 2021/11/23 10:16
* @author: LiuXS
*/
public class ComparisonUntil<T> {
private static String key;
/**
* list 与 list 进行融合
* @param searchKey 融合key
* @param valueKey 融合value
* @param gather1 主体
* @param gather2 副体
* @throws Exception 反射异常、自定义运行时异常
*/
public void postList2ListByKey(String searchKey, String valueKey, List<T> gather1, List<T> gather2) throws Exception {
if (ComparisonUntil.isEmpty(searchKey) || ComparisonUntil.isEmpty(valueKey)) throw new RuntimeException("input param:key is empty!");
key = searchKey;
Map<String, T> ga1 = List2Map(gather1);
Map<String, T> ga2 = List2Map(gather2);
key = valueKey;
ga1.entrySet().stream().forEach(entry -> {
try {
Method setMethod = getSetMethod(entry.getValue().getClass());
Method getMethod = getGetMethod(ga2.get(entry.getKey()).getClass());
setMethod.invoke(entry.getValue(), new Object[]{getMethod.invoke(ga2.get(entry.getKey()), new Object[0])});
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("java reflect error!");
}
});
}
private Method getGetMethod(Class<? extends Object> aClass) throws Exception {
StringBuilder methodName = new StringBuilder("get");
methodName.append(key.substring(0, 1).toUpperCase());
methodName.append(key.substring(1));
Method method = aClass.getMethod(methodName.toString());
method.setAccessible(true);
return method;
}
private Method getSetMethod(Class<? extends Object > aClass) throws Exception {
StringBuilder methodName = new StringBuilder("set");
methodName.append(key.substring(0, 1).toUpperCase());
methodName.append(key.substring(1));
Field field = aClass.getDeclaredField(key);
Class[] parameterTypes = new Class[1];
parameterTypes[0] =field.getType();
Method method = aClass.getMethod(methodName.toString(), parameterTypes);
method.setAccessible(true);
return method;
}
private Map<String, T> List2Map(List<T> gather) throws RuntimeException {
return gather.stream().collect(Collectors.toMap(n->{
try {
return getGetMethod(n.getClass()).invoke(n, new Object[0])+"";
} catch (Exception e) {
e.printStackTrace();
RuntimeException get_by_key_error = new RuntimeException("N to Map: get by key error");
throw get_by_key_error;
}
}, Function.identity(),(n1, n2)->n1));
}
public static boolean isEmpty(String var) {
var=var.trim();
return var == null || var.length() <= 0;
}
}