6

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


}

}
Kshitij
  • 361
  • 1
  • 9
ArunManoharan
  • 61
  • 1
  • 1
  • 4
  • 1
    @SemihEker That comment on its own means nothing. What needs to be edited? – Duncan Jones Mar 16 '15 at 15:33
  • These annotations are just hints. You need to add a validator, which would enforce these constraints, to your classpath. Have a look at [this post](http://stackoverflow.com/questions/8756768/annotations-from-javax-validation-constraints-not-working) – Kshitij Mar 16 '15 at 16:16

1 Answers1

4

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.

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
  • Do you know how to unit test this kind of method? (ex: Junit, Mockito) – ArunManoharan Mar 16 '15 at 17:06
  • @arun Please read this: http://hibernate.org/validator/documentation/getting-started/ – Moritz Petersen Mar 17 '15 at 07:33
  • thanks.... it is work for property but in my case i am using in DAO class where i passed null value to local method argument. ex: public void addEmployee( @NotNull Integer employeeId ). How can i test this method? please let me know. – ArunManoharan Mar 17 '15 at 16:59