Java Reference
In-Depth Information
Method Validation
Have you ever had the need to validate method parameters or return values without writing an extra layer of code?
The Bean Validation 1.1 release aims to solve this issue by providing the capability to utilize a programming style
known as Programming by Contract (PbC). This programming style adheres to a couple of key standards.
Validations can be expressed declaratively, without writing an extra layer of code.
Annotations are automatically included in any JavaDoc that is generated from a method that
includes validation.
Method validation takes place in a couple of different contexts. A validation can be placed on the constructor
of a class, a method of a class, or a method's parameters. All validation techniques that apply to methods of a class
also pertain to the validation of a class constructor. For a method to be capable of validation, it must be nonstatic.
Constraint annotations that are placed on a method are used to validate the return value of that method. To validate
parameters for a method, constraint annotations can be placed directly on each parameter.
it is also possible to utilize a constraint mapping file, rather than annotations, for applying constraints to a
method and/or its parameters. this technique is known as method-level overriding , and you can learn more about this
technique by visiting the online documentation at .
Declaring Parameter Constraints
To declare constraints on the parameters of a method or constructor, place annotations on the parameter(s) you want
to validate. For instance, to place a constraint on a method parameter that ensures the parameter is not null, utilize
an @NotNull annotation in the method signature. The following method signature demonstrates how to validate
parameters of a method named placeOrder :
public void createJob(
@NotNull @Size(min = 3, max = 20) Integer jobId,
@NotNull String jobTitle,
@DecimalMin("35000") BigDecimal salary,
@NotNull String division) {
Jobs newJob = new Jobs();
In the case that a parameter fails validation, it is identified in the resulting ConstraintViolation .
To gain access to the list of ConstraintViolation exceptions that are thrown, the Bean Validation API defines the
javax.validation.ParameterNameProvider API to retrieve the parameter names. To retrieve the names of the
parameters that were in violation, call the getParameterNames() method of the ParamterNameProvider .
ParameterNameProvider provider = // obtain the provider...
List<parameter name> pnames = provider.getParameterNames()
Search WWH ::

Custom Search