问题
I have an annotation
public @interface Field {
String value();
}
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
}
}
}
}
where clazz is Class<T>
but field.annotations
is empty.
How to list annotations correctly?
回答1:
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();
}
回答2:
Java annotations, by default, are not retained at runtime so you'll need to specify such:
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
public @interface Field {
String value();
}
Kotlin annotations are retained by default:
annotation class Field(val value: String)
来源:https://stackoverflow.com/questions/35927036/how-to-list-field-annotations-in-kotlin