What is the difference between @Nonnull and Objects.requireNonNull

prime :

What is the difference between following two code snippets.

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

public Integer getId(SomeObject obj){   
    Objects.requireNonNull(SomeObject, "SomeObject is null");
    // do some stuff
    return id;
}

What are the significant differences between them. And what is the correct way to do the null-check in these situations.

dasblinkenlight :

The two are complementary: @Nonnull annotation documents the fact that obj must be non-null, while Objects.requireNonNull call ensures that obj is non-null at run-time.

You should combine the two, like this:

public Integer getId(@Nonnull SomeObject obj){   
    Objects.requireNonNull(SomeObject, "SomeObject is null");
    // do some stuff
    return id;
}

Relevant documentation on @Nonnull can be found here:

Optional Type Annotations are not a substitute for runtime validation

Before Type Annotations, the primary location for describing things like nullability or ranges was in the javadoc. With Type annotations, this communication comes into the bytecode in a way for compile-time verification.

Your code should still perform runtime validation.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=448577&siteId=1