Automatically throwing IllegalArgumentException when empty values ​​are passed to the method

I am exploring the possibility of eliminating null, as well as refactoring the part of the code base that I'm working on. We upgraded to java 8, so we have it Optional<T>. To do this efficiently, we need to make sure that null is not passed to any of our methods (this is after we complete any potential NULL values ​​inside Optionalthat enter our system from external services / libraries). The obvious way to handle this is to explicitly check the null value and drop IllegalArgumentExceptionit if necessary, however this would be unreasonably verbose and manual. Is there a less manual / easier way to do this?

+4
source share
5 answers

You can use Objects::requireNonNullfor this. For example, in the constructor, you can:

this.myField = Objects.requireNonNull(myField);

He will send NullPointerExceptionif you pass null.

Avoid overuse Optional. See for example this answer .

+8
source

You can try the Lombok comment handler, which has an @NonNull annotation. Annotating a parameter using NonNull will automatically generate a zero check at compile time, so you will get either NullPointerException, or IllegalArgumentException(depending on what you like) at runtime.

+4
source

, @Nonnull ( ) , Guava:

import javax.annotation.Nonnull;
import static com.google.common.base.Preconditions.checkNotNull;

public void doSomething(@Nonnull MyClass input) {
    checkNotNull(input);
    /* Do something */
}

@Nonnull IDE , FindBugs, , . checkNotNull , NullPointerException, - null .

+3

, . , , , . , , .

.

java :

assert n != null;

, throw, AssertionError, . , , , , , , IllegalArgumentException, :

assert n != null : new IllegalArgumentException( "n cannot be null" );

, n - null, AssertionError, IllegalArgumentException. , IllegalArgumentException , "Caused by:".

, , , , , -enableassertions (-ea ), , .

+1

Source: https://habr.com/ru/post/1611343/


All Articles