什么是反射?反射如何使用?

参考链接:深入学习java源码之Class.forName()与 Class.getDeclaredField()_wespten的博客-CSDN博客

使用场景:

用Mybatis-Plus 实现列表通过动态属性排序功能时,遇到这样一个问题:前端传递实体属性字段名与排序规则(正序or倒序)如何通过驼峰转换为下划线?

解决办法为:通过参数名获取对应字段上@TableField注解里的value值则对应为数据库字段

首先在接收实体定义好统一接收参数:

    @ApiModelProperty("申请人id")
    @TableField(value = "op_id",fill = FieldFill.INSERT)
    private Integer opId;

    @ApiModelProperty("申请人名称")
    @TableField(value = "op_name",fill = FieldFill.INSERT)
    private String opName;


    @ApiModelProperty("请求参数")
    @TableField(exist = false)
    private Map<String, Object> params;

    public Map<String, Object> getParams() {
        if (params == null) {
            params = new HashMap<>(4);
        }
        return params;
    }

如何获取注解value值?直接上代码:


/**
* @param object 需要解析的对象
* @param key  需要解析的属性字段集合
* */
public static Map<String, Object> getProxyPojoValue(Object object, Set<String> key) {
        String id = null;
        // 返回参数
        HashMap<String, Object> hashMap = new HashMap<>();
        for (String s : key) {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                //在类的外面获取此类的私有成员变量的value时需配置 否则会抛异常
                field.setAccessible(true);

                // 获取表名
                TableName table = object.getClass().getAnnotation(TableName.class);
                if (table != null) {
                    String tableName = table.value();
                    //先判断key是否存在,不存在则插入到 HashMap中
                    hashMap.putIfAbsent("tableName", tableName);
                }
                // 获取主键id
                if (id == null) {
                    boolean isIdField = field.isAnnotationPresent(TableId.class);
                    if (isIdField) {
                        TableField tableField = field.getAnnotation(TableField.class);
                        if (s.toLowerCase().equals(field.getName().toLowerCase())) {
                            String tableId = tableField.value();
                            hashMap.put(s, tableId);
                            id = tableId;
                        }
                    }
                }

                // 获取字段的值
                boolean isTableField = field.isAnnotationPresent(TableField.class);
                if (isTableField) {
                    TableField tableField = field.getAnnotation(TableField.class);
                    if (s.toLowerCase().equals(field.getName().toLowerCase())) {
                        String fieldValue = tableField.value();
                        hashMap.put(s, fieldValue);
                    }
                }else if(isTableId){
                    TableId tableId = field.getAnnotation(TableId.class);
                    if (s.toLowerCase().equals(field.getName().toLowerCase())) {
                        String fieldValue = tableId.value();
                        hashMap.put(s, fieldValue);
                    }
                }
            }
        }
        return hashMap;
    }

业务实现 定义排序常量:

    /**
     * 数据库 排序字段
     */
    public static final String SORT_NAME = "sortName";

    /**
     * 数据库 排序规则
     */
    public static final String SORT_ORDER = "sortOrder";

解析方法调用:

 /**
     * 根据实体属性 排序
     *
     * */
    public static <T> LambdaQueryWrapper<T> sortOrder (Object o,Map<String, Object> map) {
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        //排序条件不为空则根据 条件排序 否则根据id降序排序
        if (StringUtils.isNotNull(map.get(SqlConstants.SORT_NAME)) && StringUtils.isNotNull(map.get(SqlConstants.SORT_ORDER))) {
            HashSet<String> set = new HashSet<>();
            set.add(map.get(SqlConstants.SORT_NAME).toString());
            //通过反射获取Value
            Map<String, Object> proxyPojoValue = SortOrder.getProxyPojoValue(o,set);
            //如果参数等于 为正序 否则为倒序
            if ("ascending".equals(map.get(SqlConstants.SORT_ORDER))) {
                wrapper.orderByAsc(proxyPojoValue.get(map.get(SqlConstants.SORT_NAME).toString()).toString());
            } else {
                wrapper.orderByDesc(proxyPojoValue.get(map.get(SqlConstants.SORT_NAME).toString()).toString());
            }
        } else {
            wrapper.orderByDesc("id");
        }
        return wrapper.lambda();
    }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐