gpt4 book ai didi

generics - Kotlin批注作为通用函数参数

转载 作者:行者123 更新时间:2023-12-02 13:38:46 25 4
gpt4 key购买 nike

我想知道是否有任何方法可以将注释用作泛型的类型参数并确定提供的输入的实例?本质上,我只想允许使用特定注释的对象被方法接受,并使用类型转换来确定基础类型。

我尝试用注释标记通用类型,但是当我尝试转换模型时,出现错误:“不兼容的类型:UsesAnnotation和MyAnnotation”

这是有道理的,因为我没有扩展MyAnnotation,所以只是在上面标记UsesAnnotation。但是有办法使这项工作吗?我只想将输入限制为使用注释的实例,然后找出作为输入提供的类型。

注释:

@MustBeDocumented
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class MyAnnotation

抽象工厂:
abstract class MyFactory<in t: Any> {
...
abstract fun genericMethod(model: T): Int
...
}

其子类:
class MyFactoryImplementation<MyAnnotationType> {
...
override fun genericMethod(model: MyAnnotation): Int {
return when (model) {
is UsesAnnotation -> 1
else -> 0
}
...
}

带注释的类:
@MyAnnotation
class UsesAnnotation

最佳答案

  • 您应该考虑的第一件事—注释不能被继承
  • 另一方面,完全可以确定是否使用带有RUNTIME保留的批注进行批注。为此,您需要将kotlin-reflect添加到您的类路径中。
    inline fun <reified T : Any> isAnnotatedWith(t: T, annotationClass: KClass<*>) = 
    isAnnotated(t::class, annotationClass)

    fun isAnnotated(inputClass: KClass<*>, annotationClass: KClass<*>) =
    inputClass.annotations.any { it.annotationClass == annotationClass }

  • 您可以从上面的代码将注释实例传递到函数 isAnnotatedWith中,并获得结果。

    关于generics - Kotlin批注作为通用函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48980170/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com