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

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

    I'm not sure this would even work; if, say, the person reference was null, what would the runtime replace it with? A new Person? That would require the Person to have some default initialization that you'd expect in this case. You may avoid null reference exceptions but you'd still get unpredictable behavior if you didn't plan for these types of setups.

    The ?? operator in C# might be best termed the "coalesce" operator; you can chain several expressions and it will return the first that isn't null. Unfortunately, Java doesn't have it. I think the best you could do is use the ternary operator to perform null checks and evaluate an alternative to the entire expression if any member in the chain is null:

    return person == null ? "" 
        : person.getName() == null ? "" 
            : person.getName().getGivenName();
    

    You could also use try-catch:

    try
    {
       return person.getName().getGivenName();
    }
    catch(NullReferenceException)
    {
       return "";
    }
    

提交回复
热议问题