Java “?” Operator for checking null - What is it? (Not Ternary!)

前端 未结 14 876
心在旅途
心在旅途 2021-01-27 15:38

I was reading an article linked from a slashdot story, and came across this little tidbit:

Take the latest version of Java, which tries to make null-poi

14条回答
  •  轮回少年
    2021-01-27 16:17

    It is possible to define util methods which solves this in an almost pretty way with Java 8 lambda.

    This is a variation of H-MANs solution but it uses overloaded methods with multiple arguments to handle multiple steps instead of catching NullPointerException.

    Even if I think this solution is kind of cool I think I prefer Helder Pereira's seconds one since that doesn't require any util methods.

    void example() {
        Entry entry = new Entry();
        // This is the same as H-MANs solution 
        Person person = getNullsafe(entry, e -> e.getPerson());    
        // Get object in several steps
        String givenName = getNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.getGivenName());
        // Call void methods
        doNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.nameIt());        
    }
    
    /** Return result of call to f1 with o1 if it is non-null, otherwise return null. */
    public static  R getNullsafe(T1 o1, Function f1) {
        if (o1 != null) return f1.apply(o1);
        return null; 
    }
    
    public static  R getNullsafe(T0 o0, Function f1, Function f2) {
        return getNullsafe(getNullsafe(o0, f1), f2);
    }
    
    public static  R getNullsafe(T0 o0, Function f1, Function f2, Function f3) {
        return getNullsafe(getNullsafe(o0, f1, f2), f3);
    }
    
    
    /** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */
    public static  void doNullsafe(T1 o1, Consumer f1) {
        if (o1 != null) f1.accept(o1);
    }
    
    public static  void doNullsafe(T0 o0, Function f1, Consumer f2) {
        doNullsafe(getNullsafe(o0, f1), f2);
    }
    
    public static  void doNullsafe(T0 o0, Function f1, Function f2, Consumer f3) {
        doNullsafe(getNullsafe(o0, f1, f2), f3);
    }
    
    
    class Entry {
        Person getPerson() { return null; }
    }
    
    class Person {
        Name getName() { return null; }
    }
    
    class Name {
        void nameIt() {}
        String getGivenName() { return null; }
    }
    

提交回复
热议问题