java泛型与扩长参数结合

结合:泛型与扩长参数达到设置参数通用效果


目录

一、扩长参数...

二、结合泛型

三:通过反射工具强行拿值,塞值


一、扩长参数...

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));
                    });
                });
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值