gpt4 book ai didi

groovy - Groovy 中的属性注释自省(introspection)

转载 作者:行者123 更新时间:2023-12-01 09:36:43 27 4
gpt4 key购买 nike

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

最佳答案

你可以这样做:

// 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 - Groovy 中的属性注释自省(introspection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6389142/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com