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

前端 未结 14 749
心在旅途
心在旅途 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:27

    There was a proposal for it in Java 7, but it was rejected:

    http://tech.puredanger.com/java7/#null

    0 讨论(0)
  • 2021-01-27 16:27

    There you have it, null-safe invocation in Java 8:

    public void someMethod() {
        String userName = nullIfAbsent(new Order(), t -> t.getAccount().getUser()
            .getName());
    }
    
    static <T, R> R nullIfAbsent(T t, Function<T, R> funct) {
        try {
            return funct.apply(t);
        } catch (NullPointerException e) {
            return null;
        }
    }
    
    0 讨论(0)
提交回复
热议问题