【问题标题】:Kotlin annotation as generic function parameterKotlin 注释作为通用函数参数
【发布时间】:2018-02-26 01:12:58
【问题描述】:

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

我尝试使用注释标记泛型类型,但是当我尝试转换模型时出现错误:“不兼容的类型: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

【问题讨论】:

    标签: generics annotations kotlin instanceof


    【解决方案1】:
    1. 您应该考虑的第一件事 - 注释不能被继承
    2. 另一方面,完全有可能确定是否使用带有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 并获取结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多