Java reflect spring中的应用场景

在spring 框架中 拼接uri 时需要输入 一组键值对,List<maps>

不使用反射自动获取getxxx 代码:

需要手动定义输入参数名

        UriComponents commonUri = UriComponentsBuilder.newInstance().
                scheme(EvUtils.HTTP).host(payload.getHostname())
                .path("xxx/xxxx/v0/json")
                .queryParams(EvUtils.getDeclaredFieldsInfo(payload).get("origin"), payload.getOrigin())
                .queryParam(EvUtils.getDeclaredFieldsInfo(payload).get("destination"), payload.getDestination())
                .queryParam(EvUtils.getDeclaredFieldsInfo(payload).get("ev_connector_type"), payload.getEv_connector_type())
                .queryParam(EvUtils.getDeclaredFieldsInfo(payload).get("ev_model"), payload.getEv_model())
                .queryParam(EvUtils.getDeclaredFieldsInfo(payload).get("battery_capacity"), payload.getBattery_capacity())
                .queryParam(EvUtils.getDeclaredFieldsInfo(payload).get("departure_battery_pct"), payload.getDeparture_battery_pct())
                .queryParam(EvUtils.getDeclaredFieldsInfo(payload).get("preferred_arrival_battery_pct"), payload.getPreferred_arrival_battery_pct())
                .queryParam(EvUtils.getDeclaredFieldsInfo(payload).get("preferred_start_charge_battery_pct"), payload.getPreferred_start_charge_battery_pct())
                .queryParam(EvUtils.getDeclaredFieldsInfo(payload).get("preferred_stop_charge_battery_pct"), payload.getPreferred_stop_charge_battery_pct())
                .build();

加入反射getxxx 方法后,使用queryParams 接受MutipleMaps

        UriComponents commonUri = UriComponentsBuilder.newInstance().
                scheme(EvUtils.HTTP).host(payload.getHostname())
                .path("xxxxx/json")
                .queryParams(EvUtils.getDeclaredFieldsInfo(payload))
                .build();

getDeclaredFieldsInfo 逻辑:

定义返回类型 MutiValueMap,接受实体Object 对象

将反射获取 实体对象带有 JsonProperty Annotation 的字段名以key 存入到map中

通过反射clazz.getMethod(拼接getxxx 方法名) 获取每个实体对象带有JsonProperty Annotation的值,将其存入map 中

最后返回该 map

    public static MultiValueMap<String, String> getDeclaredFieldsInfo(Object instance) throws IllegalAccessException {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        Class<?> clazz = instance.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Method method = null;
        for (int i = 0; i < fields.length; i++) {
            boolean annotationPresent = fields[i].isAnnotationPresent(JsonProperty.class);
            if (annotationPresent) {
                String name = fields[i].getAnnotation(JsonProperty.class).value();
                String fieldName = "get" + fields[i].getName().substring(0, 1).toUpperCase() + fields[i].getName().substring(1);
                try {
                    method = clazz.getMethod(fieldName);
                    map.add(name, String.valueOf(method.invoke(instance)));
                } catch (NoSuchMethodException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

实体类:

public class EvPlannerPayload{
   @JsonProperty("origin")
    public String origin;

    @JsonProperty("destination")
    public String destination;

}

具体例子:

 @Test
    public void testBatteryReverse(){
        EvPlannerPayload evPlannerPayload = new EvPlannerPayload();
        evPlannerPayload.setOrigin("37.98669381800903,-122.25839418347788");
        evPlannerPayload.setDestination("38.682546235798924,-121.46983905423436");
        ResponseEntity<EvPlanner> responseBody = $(EvPlannerService.class).queryByChargingPlans(evPlannerPayload);

        assertThat(responseBody.getStatusCode(), equalTo(HttpStatus.OK));
    }

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值