Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make @NotNull throw runtime exception?

Tags:

java

Is there any framework that can throw exception if I pass null as parameter to @NotNull annotation? I don't mean static analysis but run-time checks.

If not, how to implement it?

like image 833
Pan Bydlak Avatar asked Dec 20 '22 10:12

Pan Bydlak


1 Answers

If you are using Java 6 or a lower version then you can use Guava Preconditions.

Preconditions.checkNotNull(param);

However, if you using Java 7 or a higher version then there is a Utility method in Objects.

 Objects.requireNonNull(param);

And there is an overload that takes string to add a message to the NullPointerException that will be thrown

Objects.requireNonNull(param,"Param cannot be null");
like image 51
Sleiman Jneidi Avatar answered Dec 29 '22 01:12

Sleiman Jneidi