在Groovy中内省的属性注释

时间:2011-06-17 16:57:15

标签: groovy

有一种方便的方法来迭代Object的属性并检查每个的注释吗?

1 个答案:

答案 0 :(得分:8)

你可以这样做:

// First, declare your annotation
import java.lang.annotation.*

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnot {
}

// Then, define your class with it's annotated Fields
class MyClass {
  @MyAnnot String fielda
  String fieldb
  @MyAnnot String fieldc
}

// Then, we will write a method to take an object and an annotation class
// And we will return all properties of the object that define that annotation
def findAllPropertiesForClassWithAnotation( obj, annotClass ) {
  obj.properties.findAll { prop ->
    obj.getClass().declaredFields.find { 
      it.name == prop.key && annotClass in it.declaredAnnotations*.annotationType()
    }
  }
}

// Then, define an instance of our class
MyClass a = new MyClass( fielda:'tim', fieldb:'yates', fieldc:'stackoverflow' )

// And print the results of calling our method
println findAllPropertiesForClassWithAnotation( a, MyAnnot )

在这种情况下,打印出来:

[fielda:tim, fieldc:stackoverflow]

希望它有所帮助!