简体   繁体   中英

Java Auto Boxing and conditional operator

In sonar i see a major violation warning for code

  public Long getValue(FieldType fieldType) {
    Long value = paramLevelMap.get(fieldType); // ok returns Long not long
    return value == null ? UNSPECIFIED_PARAMETER_KEY : value; // complaints here
  } 

Where 'UNSPECIFIED_PARAMETER_KEY' is pvt static long , and 'value' is also long.

Boxed value is unboxed and then immediately reboxed

Its complaining on the 2nd line. I didn't quite understand it , when & how is primitive long being converted to corresponding class object ? and back ?

The return type of a ternary (or more correctly, conditional ) expression where the second and third operands consist of one primitive and one corresponding boxed version, is that of the primitive.
(For a complete analysis of the type of the conditional operator, look at the Java Specifications 15.25 .)

Since the second operand here, UNSPECIFIED_PARAMETER_KEY , is a long , and the third, value is a Long , Java has to unbox value to a long to evaluate the expression.

After this, a Long is to be returned, so value is immediately reboxed.

You can fix this by changing your constant UNSPECIFIED_PARAMETER_KEY into a Long .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM