java Bean 转 Map

2,322 阅读1分钟

通过java反射获取对象属性值, 并将其插入到 Map 中

    /**
     * 对象转换为 Map
     *
     * @param source 资源
     * @return {@link Map}
     */
    private static Map<String, Object> toMap(Object source) {
        if (source == null) return Collections.emptyMap();
        HashMap<String, Object> map = new HashMap<>();
        Field[] fields = source.getClass().getDeclaredFields();
        Stream.of(fields).forEach(it -> {
            try {
                //允许访问私有属性
                it.setAccessible(true);
                map.put(it.getName(), it.get(source));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return map;
    }