利用反射将类[以及父类]中所有非空字段填充至Map

@Slf4j
public class ReflectionUtil {

    /**
     * 类中所有非空字段填充至Map
     *
     * @param target
     * @return
     */
    public static Map<String, Object> getAllNonFieldToMap(Object target) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (target != null) {
            Class<?> clazz = target.getClass();
            List<Field> fieldList = new ArrayList<>();
            while (clazz != null) {
                fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
                clazz = clazz.getSuperclass();
            }
            for (Field f : fieldList) {
                try {
                    f.setAccessible(true);
                    Object val = f.get(target);
                    if (val != null) {
                        map.put(f.getName(), val);
                    }
                } catch (IllegalAccessException e) {
                    log.error("发生异常", e);
                }
            }
        }
        return map;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39352976/article/details/108974168