What is the difference between @Nonnull and Objects.requireNonNull

前端 未结 3 1978
感动是毒
感动是毒 2021-01-04 03:52

What is the difference between following two code snippets.

public Integer getId(@Nonnull SomeObject obj){  
    // do some stuff
    return id;
}

public In         


        
3条回答
  •  清酒与你
    2021-01-04 04:29

    One of these is an annotation which implements JSR-305, but is meant more for static analysis as opposed to a runtime guard. As I recall it, JSR-305 is a good idea in principle and a lot of things actually leverage it in some way, but it loses a lot of its bark when its utility only ever comes in the form of static analysis.

    Case in point: your IDE can leverage this to warn you of situations in which you're passing something you shouldn't, but it can't prevent you from passing null into this method when you compile.

    Objects.requireNonNull is a runtime enforcement that whatever it's passed will be a non-null reference. The compiler can't enforce this either, but at runtime should you receive a null value, you will get a NullPointerException upon executing that line of code.

    In terms of correctness, using Objects.requireNonNull is a good idea, but that depends on what your obligation is when running the application. If you must fail on a null value, then using that is fine as it will generate a runtime exception to deal with. If you can't fail on a null value, then using an if check instead would be better.

提交回复
热议问题