how to handle nulls gracefully in Java

This question already has an answer here:

  • Avoiding != null statements 58 answers

  • Apache commons-lang3 offers this:

    b.setC(ObjectUtils.defaultIfNull(a.getC(), b.getC()));
    

    But I have to admit that I'm not sure if this would really be an improvement.


    You could make a method using var args that checks all the args for your if statement:

    public boolean argsNotNull(Object ... objs) {
        boolean b = true;
        for(Object o : objs) {
            if(o == null) {
                b = false;
                break;
            }
        }
        return b;
    }
    

    Then use it like this:

    if(argsNotNull(a)) {
        Object c = a.getC();
        if(argsNotNull(b, c)) { // A null 'c' object may be valid here, depends on your logic
            b.setC(c);
        }
    }
    

    Since this method uses var args you can feed it as many args as you want, but it will not work with primitives in its current state.


    Is the bC value supposed to exactly reflect what is in aC ? In that case if aC is null then bC whould be null, and you don't really need a null check.

    Otherwise, to avoid curley braces you could do something like this :

    b.setC((a.getC() == null) ? b.getC() : a.getC());
    

    This assumes that the getter and setter from b match up exactly. If C from a is null then setC() from getC() which effectively does nothing.

    链接地址: http://www.djcxy.com/p/13306.html

    上一篇: 检查空对象

    下一篇: 如何在Java中优雅地处理空值