Pan Bydlak Pan Bydlak - 29 days ago 27
Java Question

How to make @NotNull throw runtime exception?

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?

Answer

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 to learn more.