HttpServletRequest接收参数并转化为类

public class GetParamToClass {


    public static Object setObjectFiled(HttpServletRequest request, Object object) {
        Enumeration en = request.getParameterNames();
        Field[] fields = object.getClass().getDeclaredFields();
        if (object == null) {
            return null;
        }
        try {
            while (en.hasMoreElements()) {
                String paramName = (String) en.nextElement();
                String beanSetMethod = "set" + captureName(paramName);
                for (Field field : fields) {
                    if (paramName.equals(field.getName())) {
                        String typeClass = field.getType().getSimpleName().toString();
                        if (typeClass.equals("Integer")) {
                            object.getClass().getMethod(beanSetMethod, Integer.class).invoke(object, Integer.valueOf(request.getParameter(paramName)));
                            break;
                        } else if (typeClass.equals("String")) {
                            object.getClass().getMethod(beanSetMethod, String.class).invoke(object, request.getParameter(paramName));
                            break;
                        }
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return object;
    }


    public static String captureName(String name) {
        char[] cs = name.toCharArray();
        cs[0] -= 32;
        return String.valueOf(cs);

}

}

测试:

HttpServletRequest request = ctx.getRequest();
Auth auth=Auth.builder().build();

 auth= (Auth) GetParamToClass.setObjectFiled(request,auth);




你可能感兴趣的:(http)