Monday, April 25, 2011

Is there a varargs null check function in Java or Apache Commons?

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.

From stackoverflow
  • 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;
    }
    
    Steven Huwig : Yeah I know but then the question is where to put it. ;)
    Michael Myers : Do you have a utilities class of some sort? It seems like I always end up with one.
    Steven Huwig : Yeah, it's Commons Lang, Commons IO, Commons Collections, etc...
    Michael Myers : Well, I just did some scouting around and found a couple of anyNull methods, but they seem to predate varargs.
    OscarRyz : nice question and nice answer
    Michael Myers : 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.
    Steven Huwig : Makes me wish for Hoogle: http://www.haskell.org/hoogle/
    Michael Myers : Interesting. That would indeed be useful. Joogle? Javoogle? Anyone?
    Adrian : @mmyers http://www.merobase.com
  • The best you can do with the Java library is, I think:

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

    Steven Huwig : I like that idea very much.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.