interface @ConstraintDeclaration

@ConstraintDeclaration is used to create new custom Constraint validators.

Description

Description goes here...

Declaration

package org.qi4j.api.constraint;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* All annotations that are used to trigger Constraints must
* have this annotation.
*/
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.ANNOTATION_TYPE )
@Documented
public @interface ConstraintDeclaration
{
}

Example

Let's create a @Range constraint annotation, which can be given a maximum and minimum value that is allowed. First we will need the custom annotation @Range and we need a Constraint implementation.

@ConstraintDeclaration
@Retention( RetentionPolicy.RUNTIME )
@Target( { ElementType.PARAMETER, ElementType.ANNOTATION_TYPE } )
public @interface Range
{
    double min();

    double max();
}

public class RangeConstraint
    implements Constraint<Range, Numeric>
{
    public boolean isValid( Range annotation, Numeric object )
    {
        double argument = object.doubleValue();
        return argument >= annotation.min() &&
               argument <= annotation.max();        
    }
}

To use the custom annotation above, we can apply it to a method in a MixinType.
@Constraints( RangeConstraint.class )
public interface AccountCreation
{
    Account createAccount( @Range( min=18, max=65 ) int age );
}

Qi4j and the Qi4j logo are trademarks of Richard Öberg, Niclas Hedhman and the members of the Qi4j Core Team. See Qi4j licensing for more information.
Powered by SiteVisionexternal link.