Kotlin注释作为通用函数参数

时间:2018-02-26 01:12:59

标签: generics annotations kotlin instanceof

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

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

1 个答案:

答案 0 :(得分: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 }
    
  3. 您可以从上面的代码将注释的实例传递到函数isAnnotatedWith并获得结果。

相关问题