结合:泛型与扩长参数达到设置参数通用效果
目录
一、扩长参数...
1:比较小众用法,方法可以接受长度不确定的参数,但不推荐使用,无法控制
2:结合泛型可以达到通用效果
二、结合泛型
/**
* 初始化产品名称
*
* @param t 携带有productId的domain
*/
public static <T> void initProductNames(T... t){
List<T> list= new ArrayList<>(Arrays.asList(t));
List<String> productIds = list.stream().map((item)->{
return (String)ReflectUtil.getFieldValue(item,"productId");
}).collect(Collectors.toList());
Map<String, String> map = CrmUserAndProductNameService.buildProductMaps(productIds);
Optional.ofNullable(map)
.ifPresent(maps->{
list.forEach(item->{
String productId=(String)ReflectUtil.getFieldValue(item,"productId");
ReflectUtil.setFieldValue
(item,"productName",maps.get(productId));
});
});
}
三:通过反射工具强行拿值,塞值
1:借助于hutool的ReflectUtil,不需传入class对象
2:获取字段:ReflectUtil.getFieldValue(对象,"字段名");
3:set值:ReflectUtil.setFieldValue(对象,"字段名"值);
public static <T> void initProductNames(T... t){
List<T> list= new ArrayList<>(Arrays.asList(t));
List<String> productIds = list.stream().map((item)->{
return (String)ReflectUtil.getFieldValue(item,"productId");
}).collect(Collectors.toList());
Map<String, String> map = CrmUserAndProductNameService.buildProductMaps(productIds);
Optional.ofNullable(map)
.ifPresent(maps->{
list.forEach(item->{
String productId=(String)ReflectUtil.getFieldValue(item,"productId");
ReflectUtil.setFieldValue
(item,"productName",maps.get(productId));
});
});
}