如何在 Kotlin 注释中使用类

ori*_*iaj 7 annotations kotlin

我想创建一个接收 Class 参数的注释,JAVA 中的示例应该是

@Retention(RUNTIME)
public @interface CustomAnnotation {

    Class<Comparable<?>> comparator();
}
Run Code Online (Sandbox Code Playgroud)

我想在 Kotlin 中应该是:

@Retention(AnnotationRetention.RUNTIME)
annotation class CustomAnnotation(

    val comparator: Class<Comparable<*>>
)
Run Code Online (Sandbox Code Playgroud)

但是在 Kotlin 中收到错误消息Invalid type of annotation member,那么在 Kotlin 中应该如何等效地接受类作为参数呢?

hot*_*key 6

请参阅注释的语言参考:

如果需要指定一个类作为注释的参数,请使用 Kotlin 类 ( KClass)。

因此,不要使用 Java,而是Class<Comparable<*>>使用 Kotlin 等效项KClass<Comparable<*>>::

@Retention(AnnotationRetention.RUNTIME)
annotation class CustomAnnotation(
    val comparator: KClass<Comparable<*>>
)
Run Code Online (Sandbox Code Playgroud)