如何在Kotlin中列出字段注释?

Ale*_*sky 3 annotations kotlin

我有一个注释

public @interface Field {
    String value();
}
Run Code Online (Sandbox Code Playgroud)

和java类,由它注释:

public class Animal {
    @Field("name")
    private String name;
}
Run Code Online (Sandbox Code Playgroud)

我尝试通过下一个代码列出所有字段'注释:

for(field in clazz.declaredFields){
            for(annotation in field.annotations){
                when(annotation){
                     is Field -> {
                         //do something
                     }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

clazz是哪里 Class<T>

但是field.annotations空的.

如何正确列出注释?

Vla*_*nov 6

问题不是Kotlin特有的,你只是没有Field正确配置注释.默认情况下,每个注释都保留RetentionPolicy.CLASS,这意味着它不能通过反射访问.RetentionPolicy.RUNTIME如果要在运行时访问注释,则必须使用.

@Retention(RetentionPolicy.RUNTIME)
public @interface Field {
  String value();
}
Run Code Online (Sandbox Code Playgroud)


mfu*_*n26 6

默认情况下,Java注释不会在运行时保留,因此您需要指定以下内容:

import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Retention(RUNTIME)
public @interface Field {
    String value();
}
Run Code Online (Sandbox Code Playgroud)

默认情况下保留Kotlin注释:

annotation class Field(val value: String)
Run Code Online (Sandbox Code Playgroud)