The following code is not throwing any error and it is a stand alone java program. Instead, if i pass null, it will print null in console. Please help me out, how to enable @notnull annotation.
import javax.validation.constraints.NotNull;
public class TestNotNull {
public void testNotNull(@NotNull(message = "name is compulsory") String name)
{
System.out.println(name);
}
public static void main(String... args)
{
TestNotNull testNotNull = new TestNotNull();
testNotNull.testNotNull(null);
}
}
The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
One way we can protect our code is to add annotations such as @NotNull to our method parameters. By using @NotNull, we indicate that we must never call our method with a null if we want to avoid an exception.
@NotNull : The CharSequence, Collection, Map or Array object is not null, but can be empty. @NotEmpty : The CharSequence, Collection, Map or Array object is not null and size > 0. @NotBlank : The string is not null and the trimmed length is greater than zero.
@NotNull: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, but it can be empty. @NotEmpty: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, and its size/length is greater than zero.
That won't work this way. You need to use a Bean Validation framework to trigger these annotations. The JVM itself cannot handle it. Please look at the JavaEE Tutorial for a short introduction to Java Bean Validation. A good implementation is the Hibernate Validator, which you can use in your application to validate annotated beans.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With