通过反射,设置所有为null的字段为空字符串或者对象

通过反射,设置所有为null的字段为空字符串或者对象,第1张

可以通过mvc解决,试着用反射做了一下
实际开发中的解决方法1
实际开发中的解决方法2

public class ChangeNullController {
    public static void main(String[] args) {
        Object o = new ChangeNullController().getUsers();
        long start = System.nanoTime();
        Object replace = replace(o, new HashMap<>());
        System.out.println("执行耗时:" + (System.nanoTime() - start));
        System.out.println(replace);
    }

    public List<User> getUsers() {
        ArrayList<User> users = new ArrayList<>();
        users.add(User.builder().age(18).name(null).build());
        users.add(User.builder().age(null).name("Sakura").build());

        ArrayList<Skill> skills = new ArrayList<>();
        users.add(User.builder().name("Kuria").age(18).skills(skills).build());

        skills.add(Skill.builder().name("py").time(null).build());
        skills.add(Skill.builder().name(null).time(LocalDateTime.now()).build());
        return users;
    }

    public static Object replace(Object o, HashMap<Class, HashMap<String,Method>> classMethodMap) {
        // 如果对象是集合,递归调用
        if (o instanceof Collection)
            ((Collection<?>) o).forEach(ob -> replace(ob, classMethodMap));
        // 如果对象为空返回一个空对象
        if (o == null) {
            return new Object();
        }
        Class<?> aClass = o.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            try {
                // 所有方法缓存
                HashMap<String, Method> methodMap = classMethodMap.get(aClass);
                if (ObjectUtil.isEmpty(methodMap)) {
                    // 根据class获取不到缓存,创建新的写入
                    methodMap = new HashMap<>();
                    classMethodMap.put(aClass,methodMap);
                }
                // 获取方法名
                String getMethodName = "get" + StrUtil.upperFirst(field.getName());
                // 根据方法名获取构造缓存
                Method getMethod = methodMap.get(getMethodName);
                if (ObjectUtil.isEmpty(getMethod)) {
                    // 没有缓存,新建缓存
                    getMethod = aClass.getMethod(getMethodName);
                    getMethod.setAccessible(true);
                    // 将方法写入这个class的方法缓存区,方法名作为key
                    methodMap.put(getMethodName,getMethod);
                    // 将方法缓存map写入这个class的缓存map缓存区
                    classMethodMap.put(aClass,methodMap);
                }

                Object invoke = getMethod.invoke(o);
                // 如果获取到的成员属性值是集合,进行递归调用
                if (invoke instanceof Collection) {
                    ((Collection<?>) invoke).forEach(ob -> replace(ob, classMethodMap));
                }
                // 如果属性值不为空直接跳过
                if (invoke != null)
                    continue;
                // 缓存部分如上
                String setMethodName = "set" + StrUtil.upperFirst(field.getName());
                Method setMethod = methodMap.get(aClass.getName() + setMethodName);
                if (ObjectUtil.isEmpty(setMethod)) {
                    setMethod = aClass.getMethod(setMethodName,field.getType());
                    setMethod.setAccessible(true);
                    methodMap.put(setMethodName,setMethod);
                    classMethodMap.put(aClass,methodMap);
                }
                // 根据字段类型创建新的空对象写入
                setMethod.invoke(field.getType().newInstance());
            } catch (Exception e) {
                System.out.println("出现无法直接使用反射执行的方法" + e.getMessage());
            }
        }
        return o;
    }

}

方法二:
在项目中添加配置类

/**
 * 处理 jackson 返回的null值
 * 返回json中的null值转为空字符串
 */
@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/729253.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存