spotbugs icon indicating copy to clipboard operation
spotbugs copied to clipboard

A false negative bug in the BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY detector

Open RJerrica opened this issue 2 months ago • 4 comments

In the following code example, SpotBugs fails to report a BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY warning at ​​line 5​​. The code incorrectly casts the result of Collection.toArray()to a type more specific than Object[], which is inherently unsafe. This represents a false negative in SpotBugs' detection.

Minimized Code Example

import java.util.ArrayList;
public class Main {
  public static void main(String args[]) {
    ArrayList<String> a = new ArrayList<String>();
    String s[] = (String[]) a.stream().toArray(); // should report a warning
  }
}

Execution Log of the Code Example

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String; ([Ljava.lang.Object; and [Ljava.lang.String; are in module java.base of loader 'bootstrap')
        at Main.main(Main.java:6)

RJerrica avatar Oct 06 '25 02:10 RJerrica

Thanks for opening your first issue here! :smiley: Please check our contributing guideline. Especially when you report a problem, make sure you share a Minimal, Complete, and Verifiable example to reproduce it in this issue.

welcome[bot] avatar Oct 06 '25 02:10 welcome[bot]

I suspect that this is missed because it's actually calling Stream.toArray, not Collection.toArray.

ThrawnCA avatar Oct 08 '25 00:10 ThrawnCA

Hi @ThrawnCA, this is a potential root cause, but the program also triggers the exception described in the BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY rule. Both cases should be supported.

RJerrica avatar Oct 08 '25 05:10 RJerrica

However, based on the source code, the detector does not appear to be related to Stream or Collection.

https://github.com/spotbugs/spotbugs/blob/1d1fbf04fea7991b9574893d72d6e2457790298f/spotbugs/src/main/java/edu/umd/cs/findbugs/detect/FindBadCast2.java#L492

RJerrica avatar Oct 08 '25 05:10 RJerrica