Reflection memberProperty returnType超类的类型检查失败
我得到了一个对象的实例,我扫描其中的memberProperties,这些memberProperties上附加了正确的注释。然后,我想根据它们的返回类型进行过滤。 例如,如果声明如下所示:Reflection memberProperty returnType超类的类型检查失败,reflection,kotlin,kotlin-reflect,Reflection,Kotlin,Kotlin Reflect,我得到了一个对象的实例,我扫描其中的memberProperties,这些memberProperties上附加了正确的注释。然后,我想根据它们的返回类型进行过滤。 例如,如果声明如下所示:类AutoValidatedThing:AutoValidatedUserInputComponent{…},并且目标实例包含一个@ValidComponent val someProperty:AutoValidatedThing=…,我希望将someProperty作为AutoValidatedUserI
类AutoValidatedThing:AutoValidatedUserInputComponent{…}
,并且目标实例包含一个@ValidComponent val someProperty:AutoValidatedThing=…
,我希望将someProperty
作为AutoValidatedUserInputComponent
获取到以下代码块的末尾:
val invalidOnes = this::class.memberProperties
.filter { it.javaField != null && it.javaField!!.isAnnotationPresent(ValidComponent::class.java) }
.filter { val annotations = it.javaField?.annotations; annotations != null
&& annotations.map { ann -> ann.annotationClass }.contains(ValidComponent::class)
&& it.returnType is AutoValidatedUserInputComponent }
.map { it.getter.call() as AutoValidatedUserInputComponent }
但是it.returnType是AutoValidateUserInputComponent
总是返回false
autovalidateUserInputComponent
是一个简单的界面:
interface AutoValidatedUserInputComponent {
fun blabla() : SomeType
}
调用KProperty
不会返回具有给定类型的实例,您可以对其执行is
检查-它返回一个描述该类型的反射类,具体来说,它当然不会实现您的接口。您可以调用它,检查它是否是另一个给定的KType
的子类型,而不是使用is
对于该调用,您需要为自己的接口获取KType
——为此,您可以在其KClass
上使用:
val targetType = AutoValidatedUserInputComponent::class.createType(nullable = true)
可空性部分由您决定,如果您的接口碰巧有类型参数,例如,createType
,还有其他可选参数
然后,正如我提到的,您可以使用isSubTypeOf
:
val invalidOnes = this::class.memberProperties
.filter { it.javaField != null && it.javaField!!.isAnnotationPresent(ValidComponent::class.java) }
.filter {
val annotations = it.javaField?.annotations
annotations != null
&& annotations.map { ann -> ann.annotationClass }.contains(ValidComponent::class)
&& it.returnType.isSubtypeOf(targetType)
}
.forEach {
println("Found field with annotation and given supertype: $it")
}