[Java:S1905] Necessary casts are reported as unnecessary

I don’t know, if this example hits it exactly. But let’s try.

In Eclipse (SonarLint) this line is NOT complained about. But Qube does. The project is bound to Qube.

public void foo()
{
    Runnable r = () ->
    {
        for ( X x : xs )
       {
           String s = (String) x.getObject(); // FP
       }
    };
}

The X.getObject() method returns an Object. Hence the cast to String is necessary.

There are some other cases, where this is wrong. All of them seem to be inside a lambda expression. Don’t know, if that matters.

Hello @mfroehlich,

It sounds strange that you have an issue in SonarLint but not in SonarQube, can you check your project configuration? Especially sonar.java.binaries.

I did not manage to reproduce the problem with your code, but with a somehow similar one:

void foo() {
  f(arg -> {
    String s = (String) arg.get(0)[1]; // FP
    return null;
  });
}
void f(Function<List<Object[]>, Object> function) { }

The good news is that we slightly reworked this rule in version 6.9 of the Java analyzer and that the FP is no longer present.

At this point, I have good hope that the issue you are facing will disappear when upgrading, but without any other reproducer, I can’t guarantee that.

That’s good enough for me. Thanks a lot.

Please notice, that it was the other way round here. I had an issue in Qube, but not in Lint.

I have another FP, that still exists in SonarLint 3.5.

public class C
{
    public void foo( BinaryOperator< String > op )
    {
    }
    
    public void foo( Function< String[], String > f )
    {
    }
}

new C().foo( (Function< String[], String >) this::matchingMethod );

The Java compiler (Eclipse) wants a cast here. And SonarLint marks it as unnecessary (which it actually is, but not accepted by Java (11) compiler).

I guess, it’s the same for any overloaded method with function pointer parameter like this.

What is the signature of this::matchingMethod?

I manage to reproduce a FP with this code:

  private static String matchingMethod(String s, String s1) {
    return "";
  }

  private static String matchingMethod(String[] strings) {
    return "";
  }

And same observation as the first post, we reworked ambiguous method reference (SONARJAVA-3468), this issue is not here anymore in the latest version.

public < Value > Value matchingMethod( Value... args );

If this is also solved in the future release, that’s fine. Thanks,

Thanks for the complete reproducer, I see the problem now.

I’m afraid this situation is still not correctly supported, ticket to improve this further: SONARJAVA-3615.

Best,
Quentin

Great, thanks.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.