Article From:https://segmentfault.com/q/1010000012150923
Question:

In the project, it is necessary to determine whether the parameters are empty, but it is not necessary to use the framework of spring’s valition to write a simple method of writing, the checkParamNotNull method. A parameter can be well judged, but when multiple parameters are neededYou need to call many times.

// If a three parameter needs to be judged Param1, param2, param3CheckParamNotNull (Param1, "dispalyName1");CheckParamNotNull (param2, "dispalyName1");CheckParamNotNull (param3, "dispalyName1");

But want to pass in, this way to call

checkParamsNotNull(param1, param2, param3);

The way you can think of it now is to use itVariable length parameterOr list is sent in and judged separately, then the wrong message is called parameter name.

I’d like to ask for some advice.
Is this a suitable way? Is there any better way?
There are not many places to see in the normal way. Are there any bad places?

thx

Answer 0:
public static void checkParamsNotNull(String errorMessage,Object... params) {
        if (params != null && params.length > 0) {
            for (Object element : params) {
                if (element == null) {
                    throw new IllegalArgumentException(errorMessage);
                }
            }
    }
}

This assertion is quite ready-made and does not need to be written by itself. There is Assert in Spring.

Leave a Reply

Your email address will not be published. Required fields are marked *