Skip to content

Instantly share code, notes, and snippets.

@tolitius
Created March 7, 2012 09:19
Show Gist options
  • Save tolitius/1992123 to your computer and use it in GitHub Desktop.
Save tolitius/1992123 to your computer and use it in GitHub Desktop.
Groovy POGO Validation [adopted some time ago from a no longer existing Spock's groovy extensions]
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 ) )
}
}
@tolitius
Copy link
Author

tolitius commented Mar 7, 2012

here is the removed origin: pniederw/groovy-extensions@05edf7c#diff-21

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment