@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)
public @interface ConstraintDefinition
The constraint class must have a public constructor that accepts the annotation that has the ConstraintDefinition annotation. It must also define several "constrain" methods which perform constraint checks on specific property types.
Example integer constraint:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@ConstraintDefinition
public @interface IntegerConstraint {
int min() default Integer.MIN_VALUE;
int max() default Integer.MAX_VALUE;
public static class Constraint {
private final String propertyName;
private final int min;
private final int max;
// Constructor may throw a MalformedTypeException if
// params supplied by annotation are illegal.
/**
* @param type optional type of object that contains the constrained property
* @param propertyName name of property with constraint
* @param annotation specific annotation that binds to this constraint class
*/
public Constraint(Class type, String propertyName, IntegerConstraint annotation) {
this.propertyName = propertyName;
this.min = annotation.min();
this.max = annotation.max();
}
// Define a constrain method for each supported property type.
/**
* @param propertyValue specific value to constrain
*/
public void constrain(int propertyValue) throws IllegalArgumentException {
if (propertyValue < min || propertyValue > max) {
throw new IllegalArgumentException
("Value for \"" + propertyName + "\" must be in range " +
min + ".." + max + ": " + propertyValue);
}
}
}
}
The newly defined integer constraint can be applied to property mutators.
public interface UserInfo extends Storable {
...
int getAge();
// Constraint is called before setting age.
@IntegerConstraint(min=0, max=120)
void setAge(int value);
}
| Modifier and Type | Optional Element and Description |
|---|---|
java.lang.Class |
implementation
Specify class which will perform constraint checking.
|
public abstract java.lang.Class implementation
(Class type, String propertyName, Annotation),
where Annotation refers to the annotation with the
constraint definition.
The implementation class need not be explicitly specified. By default, the constraint class must be a static inner class of the annotation, named "Constraint".
Copyright © 2006-2013 Amazon Technologies, Inc.. All Rights Reserved.