如何在Kotlin中列出字段注释? [英] How to list field annotations in Kotlin?
本文介绍了如何在Kotlin中列出字段注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个注释
public @interface Field {
String value();
}
和带有注释的java类:
and java class, annotated by it:
public class Animal {
@Field("name")
private String name;
}
我尝试通过下一个代码列出所有字段的注释:
I try to list all field' annotations by the next code:
for(field in clazz.declaredFields){
for(annotation in field.annotations){
when(annotation){
is Field -> {
//do something
}
}
}
}
克拉兹是Class<T>
但field.annotations
为空.
如何正确列出注释?
推荐答案
问题不是Kotlin特有的,您只是没有正确配置Field
批注.默认情况下,每个注释都通过 RetentionPolicy.CLASS
,这意味着将无法通过反射对其进行访问.您必须使用 RetentionPolicy.RUNTIME
如果要在运行时中访问注释.
The issue isn't Kotlin specific, you just haven't configured Field
annotation properly. By default, each annotation is retained with RetentionPolicy.CLASS
, meaning it won't be accessible via reflection. You have to use RetentionPolicy.RUNTIME
if you want to access the annotation in the runtime.
@Retention(RetentionPolicy.RUNTIME)
public @interface Field {
String value();
}
这篇关于如何在Kotlin中列出字段注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文