将Object转换成Map

/**
     * 获取要查询对象的方法和值,以Map返回
     * @param  model
     *            实体类
     * @return
     * @throws  NoSuchMethodException
     * @throws  IllegalAccessException
     * @throws  IllegalArgumentException
     * @throws InvocationTargetException
     */
    public static Map<String, String> getSearchProperty(Object model)
            throws NoSuchMethodException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Map<String, String> resultMap = new HashMap<String, String>();
        // 获取实体类的全部属性,返回Field数组
        Field[] field = model.getClass().getDeclaredFields();
        for (int i = 0; i < field.length; i++) { // 遍历全部属性
            String name = field[i].getName(); // 获取属性的名字
            // 获取属性的类型
            String type = field[i].getGenericType().toString();
            if (type.equals("class java.lang.String")) { // 若是type是类类型,则前面包含"class ",后面跟类名
                // 生成get方法
                Method m = model.getClass().getMethod(
                        "get" + UpperCaseField(name));
                String value = (String) m.invoke(model); // 调用getter方法获取属性值
                if (value != null) {
                    resultMap.put(name, value);
                }
            }
        }
        return resultMap;
    }java


/**
     * 将属性首字母转化为大写
     *
     * @param fieldName
     *            属性名称
     * @return
     */
    private static String UpperCaseField(String fieldName) {
        fieldName = fieldName.replaceFirst(fieldName.substring(0, 1), fieldName
                .substring(0, 1).toUpperCase());
        return fieldName;
    }

数组

相关文章
相关标签/搜索