功能說明

比如前端網頁傳遞過來的數據是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);}