Skip to content

Instantly share code, notes, and snippets.

@gAmUssA
Forked from tolitius/validator-test.groovy
Created October 8, 2013 17:28
Show Gist options
  • Save gAmUssA/6888324 to your computer and use it in GitHub Desktop.
Save gAmUssA/6888324 to your computer and use it in GitHub Desktop.
class Person {
@Require( { it ==~ /[a-z A-Z]*/ } )
String name
@Require( { it in (0..130) } )
int age
}
def validator = new Validator()
def rod = new Person( name: "Rod Checz", age: 21 )
assert validator.isValid( rod )
def rodWannabe = new Person( name: "I am Rod Wannabe!", age: 17 )
assert !validator.isValid( rodWannabe )
def rodIsTooOld = new Person( name: "Rod is Old", age: 365 )
assert !validator.isValid( rodIsTooOld )
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
@Retention( RetentionPolicy.RUNTIME )
@interface Require {
Class value()
}
class Validator {
def isValid( pogo ) {
pogo.getClass().declaredFields.every { isValidField( pogo, it ) }
}
def isValidField( pogo, field ) {
def annotation = field.getAnnotation( Require )
!annotation || meetsConstraint( pogo, field, annotation.value() )
}
def meetsConstraint( pogo, field, constraint ) {
def closure = constraint.newInstance( null, null )
field.setAccessible( true )
closure.call( field.get( pogo ) )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment