1

java.util.Objects.isNull vs object == null

Using java 8. seems Objects.isNull() is the recommended way, is there a way to get warning if we write like this "object == null" ?

Thanks !

user3552178
  • 2,719
  • 8
  • 40
  • 67
  • 1
    [Create a custom inspection](https://www.jetbrains.com/help/idea/creating-custom-inspections.html) – Michał Krzywański Jun 24 '20 at 17:00
  • 3
    `isNull` is primarily there to be used as a lambda, as described in the question you linked. There's no "recommendation" to use it instead of `== null`. – chrylis -cautiouslyoptimistic- Jun 24 '20 at 17:05
  • 1
    Think of it this way: the only way that `if (foo = null)` even compiles is if `foo` is specifically a `Boolean` and in that case it will *always* throw a `NullPointerException`. So I don't think it's very likely that a typo like that ever goes unnoticed. – Joachim Sauer Jun 24 '20 at 17:33
  • Thanks for guys above, someone in the team has a very strong opinion, otherwise cannot pass code review. – user3552178 Jun 24 '20 at 21:01
  • I think your starting point is wrong. The [Javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#isNull-java.lang.Object-) is quite clear about recommending how to use this: `This method exists to be used as a Predicate, filter(Objects::isNull)` – vegemite4me Mar 08 '21 at 20:05

1 Answers1

0

In the code sample as follows:

    public static void main(String... args) {
    List<String> list = Arrays.asList("a", "b", null, null);
    boolean b = list.stream().anyMatch(str -> str == null);
    System.out.println(b);
}

IntelliJ IDEA will suggest you a fix to change the lambda with method reference, and you will have:

boolean b = list.stream().anyMatch(Objects::isNull);

instead.

The inspection that is responsible for the fix is Java | Java language level migration aids | Java 8 | Lambda can be replaced with method reference.

Olga Klisho
  • 1,206
  • 5
  • 7