Groovy中的属性注释内省

Groovy中的属性注释内省,groovy,Groovy,是否有一种方便的方法来迭代对象的属性并检查每个属性的注释?您可以这样做: // 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

是否有一种方便的方法来迭代对象的属性并检查每个属性的注释?

您可以这样做:

// 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]

希望有帮助

我想没有。也许你可以给我们更多关于你想要达到的目标的信息。谢谢,这很有用!Groovy并不是我所期望的超级优雅,但它的工作原理是:)@pavlo Inegant与java版本的相同东西相比?使用Groovy 2.4.5,这似乎是实现它的方法:`def findAllPropertiesForClassWithAnotation(obj,annotClass){obj.properties.findAll{prop->obj.class.declaredFields.find{field->field.name==prop.key&&field.declaredAnnotations*.annotationType().contains(annotClass)}`Using
class.declaredFields
会导致问题,如果属性是在一个超类中定义的,并且通过
traits
添加的属性的名称可能与您不期望的名称不匹配,如果不进行操作的话。