Java – null is a good way to check a long list of parameters

Suppose that all parameters of the same type for some methods are long I have similar operations on each parameter (if they are not null) Suppose I can't control method signature because the class implements an interface

For example Something as simple as this A set of string parameters

public void methodName(String param1,String param2,String param3,String param4){

    //Only print parameters which are not null: 

    if (param1 !=null)
        out.print(param1);

    if (param2 !=null)
        out.print(param2);

    if (param3 !=null)
        out.print(param3);

    if (param4 !=null)
        out.print(param4);
}

Is there any way to traverse the list of string parameters to check if they are empty and print them without having to refer to each variable separately?

Solution

You can just do it

for (String s : Arrays.asList(param1,param2,param3,param4)) {
    if (s != null) {
        out.print(s);
    }
}

or

for (String s : new String[] {param1,param4}) {
    if (s != null) {
        out.print(s);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>