Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax @notnull is not working

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);


}

}
like image 547
arun Avatar asked Mar 16 '15 15:03

arun


People also ask

What is @NotNull annotation in Java?

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.

What is @NotNull annotation in Spring boot?

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.

What is the difference between @NotNull and @NotBlank?

@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.

What is the difference between @NotNull and @NotEmpty?

@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.


1 Answers

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.

like image 89
Moritz Petersen Avatar answered Oct 16 '22 00:10

Moritz Petersen