nibin
06/09/2016, 10:10 PMimport java.lang.annotation.*
// an annotation class
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnot {
String id();
}
// class members are annotated
class MyClass {
@MyAnnot(id="a")
String fielda
String fieldb
@MyAnnot(id="c")
String fieldc
}
def findAnnotatedFieldValue( obj, annotClass, id) {
def prop = obj.properties.find { prop ->
obj.getClass().declaredFields.find { field ->
field.name == prop.key && field.declaredAnnotations.find { annot->
return annot.id() == id
}
}
}
return prop
}
// define an object of class
MyClass a = new MyClass( fielda:'valuea', fieldb:'valueb', fieldc:'valuec' )
// verify the results
assert findAnnotatedFieldValue( a, MyAnnot, "a" ).value == "valuea"
assert findAnnotatedFieldValue( a, MyAnnot, "c" ).value == "valuec"