spotbugs icon indicating copy to clipboard operation
spotbugs copied to clipboard

SpotBugs fails to detect impossible cast (String to Integer)

Open RJerrica opened this issue 2 months ago • 2 comments

Hi, in the provided code example, SpotBugs fails to report a BC_IMPOSSIBLE_CAST warning at ​​line 10​​, where an impossible cast between Integer and String occurs. Although the code compiles, this operation will always throw a ClassCastExceptionat runtime if executed.

import java.io.FileInputStream;
import java.io.FileNotFoundException;

class C {
    private Object field;
    public void method() {
        if (field instanceof String) {
            try {
                String fieldText = (String) field;
                field = Integer.valueOf(fieldText); // should report a warning
                FileInputStream fis = new FileInputStream("path");
                // ...
            } catch (FileNotFoundException e) {
                field = "str";
            }
        }
    }
}

RJerrica avatar Oct 05 '25 16: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 05 '25 16:10 welcome[bot]

I don't think this would throw a ClassCastException if field contains a valid numeric string value like "123". And shouldn't it be a NumberFormatException otherwise?

Edit: Tried making a simple runner for this by adding a main method that constructed a C and called method, it just ran silently without errors. Pretty sure field is just null and the instanceof condition fails so the whole block is skipped. How are you actually using this?

ThrawnCA avatar Oct 08 '25 00:10 ThrawnCA