Property annotations introspecting in Groovy

2020-03-25 23:31发布

is there a convenient way to iterate Object's properties and to check annotations for each?

标签: groovy
1条回答
够拽才男人
2楼-- · 2020-03-26 00:01

You can do it this way:

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

In this instance,this prints out:

[fielda:tim, fieldc:stackoverflow]

Hope it helps!

查看更多
登录 后发表回答