views:

508

answers:

3

I've got four variables and I want to check if any one of them is null. I can do

if (null == a || null == b || null == c || null == d) {
    ...
}

but what I really want is

if (anyNull(a, b, c, d)) {
    ...
}

but I don't want to write it myself. Does this function exist in any common Java library? I checked Commons Lang and didn't see it. It should use varargs to take any number of arguments.

+13  A: 

I don't know if it's in commons, but it takes about ten seconds to write:

public static boolean anyNull(Object... objs) {
    for (Object obj : objs)
        if (obj == null)
            return true;
    return false;
}
Michael Myers
Yeah I know but then the question is where to put it. ;)
Steven Huwig
Do you have a utilities class of some sort? It seems like I always end up with one.
Michael Myers
Yeah, it's Commons Lang, Commons IO, Commons Collections, etc...
Steven Huwig
Well, I just did some scouting around and found a couple of anyNull methods, but they seem to predate varargs.
Michael Myers
nice question and nice answer
OscarRyz
I tried searching Google Code (http://code.google.com/), but I'm not exactly sure how to formulate the search. The basic structure of the code would look something like this, but the names could be almost anything.
Michael Myers
Makes me wish for Hoogle: http://www.haskell.org/hoogle/
Steven Huwig
Interesting. That would indeed be useful. Joogle? Javoogle? Anyone?
Michael Myers
@mmyers http://www.merobase.com
Adrian
+6  A: 

The best you can do with the Java library is, I think:

if (asList(a, b, c, d).contains(null)) {
Tom Hawtin - tackline
With a static import of java.util.Arrays.asList, I presume?
Michael Myers
Yes. You have to import it someway. Although it is a bit of a cheat...
Tom Hawtin - tackline
close to literate programming
OscarRyz
A little slower, too, one would guess, but no external libraries and no figuring out where to put the anyNull method.
Michael Myers
+2  A: 

You asked in the comments where to put the static helper, I suggest

public class All {
    public static final boolean notNull(Object... all) { ... }
}

and then use the qualified name for call, such as

assert All.notNull(a, b, c, d);

Same can then be done with a class Any and methods like isNull.

Adrian
I like that idea very much.
Steven Huwig