Kotlin反射检查可为空的类型
如何测试KType变量是否持有可空的Kotlin类型的值(例如Int?)?
How can I test if a KType variable holds a value of a nullable kotlin type, (e.G. Int?)?
我有
var type: KType
来自KProperty<*>.returnType
的
变量,我需要检测它是否等于某些kotlin类型(Int,Long等).这适用于:
variable coming from a KProperty<*>.returnType
and I need to detect if it is equal to certain kotlin types (Int, Long, etc). This works with:
when (type) {
Int::class.defaultType -> ...
Long::class.defaultType -> ...
else -> ...
}
但这仅适用于不可为null的类型,因此第一个分支与Int不匹配?但是我还无法弄清楚如何检测类型是否为Int?否则就不那么明显了
but this only works for non-nullable types, so the first branch does not match to Int? However I was yet unable to figure out how I could detect is type is Int? other then to obvious but not so nice
type.toString().equals("kotlin.Int?")
As you can see from the KType API documentation, its interface is far from complete. Currently almost for any operation you have to resort to Java reflection with the .javaType
extension property available on KType
instances. (By the way, this is surely going to be addressed in Kotlin 1.1.)
在您的情况下,您必须检查该类型是否可为空,并且其Java类型是否等于所需的原始类的Java类型,例如:
In your case, you have to check if the type is nullable and its Java type is equal to that of the required primitive class, e.g.:
val isNullableInt = type.isMarkedNullable &&
type.javaType == Int::class.defaultType.javaType
我还可以提出一个有趣的解决方法,它可能更适合您的用例:您可以声明具有所需类型的私有函数,并在运行时使用反射与该函数的返回类型进行比较:
I can also present a funny workaround which may be more suitable for your use case: you can declare a private function with the needed type and use reflection to compare against the return type of that function at runtime:
// Only return type of this function is used
fun _nullableInt(): Int? =
TODO() // Doesn't matter, it never gets called
...
val isNullableInt = type == ::_nullableInt.returnType