Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top