Kotlin 注解作为通用函数参数
Kotlin annotation as generic function parameter
我想知道是否有任何方法可以将注释用作泛型的类型参数并确定所提供输入的实例?本质上,我只想允许方法接受使用特定注释的对象,并使用类型转换来确定基础类型。
我尝试用注解标记通用类型,但是当我尝试转换模型时出现错误:"Incompatible types: UsesAnnotation and 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:
class MyFactoryImplementation<MyAnnotationType> {
...
override fun genericMethod(model: MyAnnotation): Int {
return when (model) {
is UsesAnnotation -> 1
else -> 0
}
...
}
注解class:
@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
并获得结果。
我想知道是否有任何方法可以将注释用作泛型的类型参数并确定所提供输入的实例?本质上,我只想允许方法接受使用特定注释的对象,并使用类型转换来确定基础类型。
我尝试用注解标记通用类型,但是当我尝试转换模型时出现错误:"Incompatible types: UsesAnnotation and 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:
class MyFactoryImplementation<MyAnnotationType> {
...
override fun genericMethod(model: MyAnnotation): Int {
return when (model) {
is UsesAnnotation -> 1
else -> 0
}
...
}
注解class:
@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
并获得结果。