Using @NonNull for checking class members too

2.5k views Asked by At

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. :)

3

There are 3 answers

2
borjab On

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:

@RequestMapping(value = "/MyPath", method = RequestMethod.POST)
public String postCostForm(Model model, @Valid MyForm myForm, BindingResult result){                        
        if(result.hasErrors()){             
            for(ObjectError error : result.getAllErrors()){
                  // Do something
            }                               
            return "/error";
        }else{
            return "/success";
        }
}

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.

3
Arjit On

Use @Required annotation in Spring's

private String string1;

@Required
public void setString1(String string1) {
  this.string1= string1;
}
5
shazin On
class A {
    @NotNull
    private String string1; /** Cannot be null */
    @NotNull
    private String string2; /** Cannot be null */
    private String string3; /** Can be null */
}

And in the method signature have @Valid

public int function(@Valid A object)