How to list field annotations in Kotlin?

◇◆丶佛笑我妖孽 提交于 2020-01-24 11:44:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!