How do I make an @NotNull throw runtime exception?

Is there any framework that can throw an exception if I pass null as a parameter to the annotation @NotNull

? I don't mean static analysis, but runtime checks.

If not, how to implement it?

+3


source to share


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 to find out more.

+3


source


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







All Articles