How do I make an @NotNull throw runtime exception?
2 answers
Lombok @NonNull generates this boilerplate for you. Instead of annotation method with @NotNull, you comment out the @NonNull parameter instead.
import lombok.NonNull;
public class NonNullExample extends Something {
private String name;
public NonNullExample(@NonNull Person person) {
super("Hello");
//// if (person == null) {
//// throw new NullPointerException("person");
//// }
this.name = person.getName();
}
}
Look at the many questions marked lombok to find out more.
+3
source to share
If you are using Java 6 or lower you can use Guava
Preconditions
.
Preconditions.checkNotNull(param);
However, if you are 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 a string to add a message to NullPointerException
to be fetched
Objects.requireNonNull(param,"Param cannot be null");
+7
source to share