在Groovy中反思的属性注释 [英] Property annotations introspecting in Groovy
本文介绍了在Groovy中反思的属性注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方便的方法来迭代Object的属性并检查每个注释?
你可以这样做:
//首先,声明注释
import java.lang.annotation。*
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnot {
}
//然后,用你的类定义它被注释Fields
class MyClass {
@MyAnnot String fielda
String fieldb
@MyAnnot String fieldc
}
//然后,我们将编写一个方法来获取对象和注解类
//我们将返回定义该注释的对象的所有属性
def findAllPropertiesForClassWithAnotation(obj,annotClass){
obj.properties .findAll {prop - >
obj.getClass()。declaredFields.find {
it.name == prop.key&& annotclass in.declaredAnnotations * .annotationType()
}
}
}
//然后,定义我们类的一个实例
MyClass a = new MyClass(fielda:'tim',fieldb:'yates',fieldc:'stackoverflow')
//打印调用我们方法的结果
println findAllPropertiesForClassWithAnotation(a,MyAnnot)
在这个例子中,打印出来:
[fielda:tim,fieldc:stackoverflow]
它有帮助!
is there a convenient way to iterate Object's properties and to check annotations for each?
解决方案
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!
这篇关于在Groovy中反思的属性注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文