编程知识 cdmana.com

Record a trap in a Java ternary expression

I met a strange one today Java Null pointer exception in ternary expression . I wish to record .

Code

The code is as follows :

Integer itemVO = null;
Integer globleLatenessToleranceUseAlternate = null;
Integer latenessToleranceUseAlternate =
    (itemVO == null ? globleLatenessToleranceUseAlternate : itemVO.intValue());

As you can see from the code above : When itemVO Isn't empty , Just take itemVO Value ; otherwise , Just take globleLatenessToleranceUseAlternate Value .

reason

But the problem is globleLatenessToleranceUseAlternate. When itemVO It's empty time , If you take globleLatenessToleranceUseAlternate, You don't get a value null, It is Java Will be able to globleLatenessToleranceUseAlternate Carry out an automatic unpacking process . in short , The gain is globleLatenessToleranceUseAlternate.intValue(), here , because globleLatenessToleranceUseAlternate Itself is null, therefore globleLatenessToleranceUseAlternate.intValue() Causes a null pointer, so .

solution

Modify as follows to solve :

Integer itemVO = null;
Integer globleLatenessToleranceUseAlternate = null;
Integer latenessToleranceUseAlternate;

if (itemVO != null) {
    latenessToleranceUseAlternate = itemVO.intValue();
} else {
    latenessToleranceUseAlternate = globleLatenessToleranceUseAlternate;
}

It is worth noting that , In the new edition of JDK and Eclipse in , Will give friendly hints , In order to effectively avoid the above problems . The tips are as follows :

Null pointer access: This expression of type Integer is null but requires auto-unboxing

Reference

版权声明
本文为[Board]所创,转载请带上原文链接,感谢

Scroll to Top