Reputation: 567
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?
Upvotes: 4
Views: 5785
Reputation: 174
Lombok @NonNull generates those boilerplate for you. Instead of annotating method with @NotNull, you annotate the parameter @NonNull 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();
}
}
See the many questions tagged lombok to learn more.
Upvotes: 4
Reputation: 23329
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");
Upvotes: 7