[Dry goods] Java judges whether the value of some attributes in an object is empty

        An object in Java has multiple attributes, and some attributes need to be "non-null" in the work. If IFNULL is used, there will be a lot of redundant codes, the code readability is poor, and the later maintenance workload will be huge.

        If the object adds and deletes attributes, the judgment code needs to be hard-coded again, which violates the OCP in SOLID, and using IFNULL to judge empty time does more harm than good.

        In view of the situation of efficient development, use reflection technology to organize tool classes, simplify engineering code, and improve work efficiency.

1. Test case:

package com.xhh.base.test;

import lombok.Data;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

@Data
public class AgentTimeHourEntity {

    private String statAt;
    private Integer companyId;
    private Integer agentId;
    private Integer workTime;
    // 此处省略其他属性...

    public static void main(String[] args) {
        AgentTimeHourEntity agentTimeHour = new AgentTimeHourEntity();
        agentTimeHour.setStatAt("2022-10-10 08:00:00");
        agentTimeHour.setCompanyId(1);
        agentTimeHour.setAgentId(1);
        agentTimeHour.setWorkTime(1800);

        // 因 WorkTime 属性有值,故输出结果为:true
        System.out.println(ObjectUtil.checkObjFieldsIsNotNull(agentTimeHour, Arrays.asList("statAt", "companyId", "agentId")));
    }

}

2. Tools are as follows:

package cn.xhh.base.util;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ObjectUtil {

    /**
     * 判断对象中部分属性值是否不为空
     *
     * @param object       对象
     * @param excludeFieldNames 选择忽略校验的属性名称List集合
     * @return
     */
    public static boolean checkObjFieldsIsNotNull(Object object, List<String> excludeFieldNames) {
        if (null == object) {
            return false;
        }

        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (!excludeFieldNames.contains(f.getName()) && f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

}

Reference article:

Detailed Explanation of Java Reflection Technology - Alibaba Cloud Developer Community

SOLID Principles: The Definitive Guide - Alibaba Cloud Developer Community

Guess you like

Origin blog.csdn.net/u010953816/article/details/127284235