Let's say I have a class that has 3 members:
Class A {
private String string1; /** Cannot be null */
private String string2; /** Cannot be null */
private String string3; /** Can be null */
}
I have 2 method that accepts an object of this class as a parameter. One of the methods needs to check that the non nullable fields are present while in the other one, it doesn't matter:
public int func1(A object); /** Check non nullable fields */
public int func2(A object); /** No check required */
Is there any clean way to do it? Using @NonNull annotations or something?
I have tried various ways but none of them work. All the NonNull only help make sure that the setter doesn't get null as the parameter. Or that the object itself isn't null.
I can't seem to find something that does this kind of recursive null check on the object.
It'd be great if any of you could help. :)
You need a bean Validator, a class used to check that the bean is OK. In Spring there are a number of implementations. For example, see SmartValidatorand LocalValidatorFactoryBean
The @valid annotation is a nice way to call automagically the validator. As you are using Spring you can avoid the manual creation of the validator. It only works if the method is called by Spring (or any equivalent container). You may get the validation results in a BindingResult object. For example:
Validation is very powerfull and sometimes complex. You may create groups of validation and check just one group of them. You can create your custom constraint tags, you can call validation methods and you may customize and internationalize the messages returned if the validation fails.