One of them is an annotation that implements JSR-305 , but is intended for static analysis, and not to protect run-time. As far as I remember, JSR-305 is a good idea in principle, and many things actually somehow use it, but it loses a lot of its bark when its usefulness only ever comes in the form of static analysis.
Example: your IDE can use this to alert you to situations in which you are passing something that you should not, but that cannot stop you from passing null to this method when compiling.
Objects.requireNonNull is a enforcement that, no matter how it is passed, will be a reference to a non-zero value. The compiler cannot execute this either, but at runtime, if you get a null value, you will get a NullPointerException when this line of code is executed.
In terms of correctness, using Objects.requireNonNull is a good idea, but it depends on what your responsibility is when starting the application. If you must fail on a zero value, then use this normally, as it will throw an exception at runtime. If you cannot fail at a zero value, it is better to use an if check instead.
Makoto
source share