What is the difference between @Nonnull and Objects.requireNonNull

前端 未结 3 2114
感动是毒
感动是毒 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:18

    The difference is that in the first case it's a hint for a compiler and IDE that the argument should not be null, so when you write getId(null)you'll get an error. But someone may pass null value in runtime.

    As for the second case, it's a kind of defensive programming, when you fail-fast with a precondition that the argument should not be null.

提交回复
热议问题