Kotlin注释作为通用函数参数



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

我尝试用注释标记通用类型,但是当我尝试施放模型时,我会遇到一个错误:"不兼容类型:使用Andantation和Myannotation"

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

注释:

@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. 您考虑的第一件事 - 注释不能继承
  2. 另一方面,
  3. 完全有可能用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并获得结果。

最新更新