功能说明

比如前端网页传递过来的数据是id=123&name=zhangsan&age=23
通过工具类,最终能够将键值对赋给User对象

user{id:123,name:zhangsan,age:23}

实体类

@Datapublic class User {    /**     * 昵称     */    private String nickname;    /**     * 登录名     */    private String account;    /**     * 电话     */    private String tel;}

工具类

public class SearchConditionUtil {    /**     * 调用obj的set方法将searchCondition的值设置到obj中     *     * @param obj     * @param searchCondition 查询条件     * @param      */    public static  void initParam(T obj, SearchCondition searchCondition) {        if (searchCondition != null) {            String searchKey = searchCondition.getSearchKey();            String searchValue = searchCondition.getSearchValue();            if (searchKey != null && searchKey.length() > 0 && searchValue != null && searchValue.length() > 0) {                try {                    Method method = obj.getClass().getMethod("set" + StringUtil.firstLatterUpper(searchKey), String.class);                    method.invoke(obj, searchValue);                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {                    e.printStackTrace();                }            }        }    }}

SearchCondition是用来封装查询数据(key和value)的实体类,具体代码如下:

@Getter@Setter@ToString@Builder@AllArgsConstructor@NoArgsConstructorpublic class SearchCondition {    /**     * 条件查询的key     */    private String searchKey;    /**     * 条件查询的value     */    private String searchValue;}

测试代码

public static void main(String[] args) throws Exception {    User user = new User();    String searchKey = "tel";    String searchValue = "432423";    SearchCondition searchCondition = new SearchCondition(searchKey, searchValue);    initParam(user, searchCondition);    System.out.println(user);}