Fix of java.S1905 can lead to a compilation failure

  • Windows 10
  • SonarLint
  • Java

For the code below:

  List<Class<?>> m(Path path) throws IOException {
    try (var stream = Files.walk(path)) {
      return -> {
        var className = p.toString();
        try {
          return Class.forName(className);
        } catch (ClassNotFoundException e) {
          return (Class<?>) null;

There is a lint that casting to Class<?> is unnecessary, and suggests its removal, however doing so would lead to a compilation failure (by IntelliJ and Maven).

Please note that “className = p.toString()” is not logical, but is is a shorthand for the deduction of the correct class name.

Hi @Ahmed_Ashour,

Welcome to the community,

Thank you for reporting the false positive. The reproducer is very neat. I have created a ticket and you can track its progress here. For now, you can mark the issue as a false positive.