A false negative bug in the BC_IMPOSSIBLE_DOWNCAST_OF_TOARRAY detector
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)
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.
I suspect that this is missed because it's actually calling Stream.toArray, not Collection.toArray.
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.
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