-
-
Save gAmUssA/6888324 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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