如何在Kotlin中获取KType? [英] How to obtain a KType in Kotlin?
问题描述
我正在尝试在Kotlin中使用反射功能,但似乎无法理解如何获取KType值.
I'm experimenting with the reflection functionality in Kotlin, but I can't seem to understand how to obtain a KType value.
假设我有一个将短语映射到对象工厂的类.如有歧义,用户可以提供type
参数,将搜索范围缩小到仅返回该类型对象(或某些子类型)的工厂.
Suppose I have a class that maps phrases to object factories. In case of ambiguity, the user can supply a type
parameter that narrows the search to only factories that return that type of object (or some sub-type).
fun mapToFactory(phrase: Phrase,
type: KType = Any::class): Any {...}
type
需要接受几乎所有东西,包括Int
,根据我的经验,这似乎有些特殊.默认情况下,它应该类似于Any
,表示不排除任何工厂".
type
needs to accept just about anything, including Int
, which from my experience seems to be treated somewhat specially. By default, it should be something like Any
, which means "do not exclude any factories".
如何为type
分配默认值(或任何值)?
How do I assign a default value (or any value) to type
?
推荐答案
根据您的描述,听起来您的函数应该使用KClass
参数(而不是KType
),并使用isSubclass
检查传入的对象,而不是isSubtype
.
From your description, sounds like your function should take a KClass
parameter, not a KType
, and check the incoming objects with isSubclass
, not isSubtype
.
类型(在kotlin-reflect
中用KType
表示)通常来自代码中声明的签名.它们表示一组广泛的值,这些值将函数用作参数或返回值.类型由类,该类的通用参数和可空性组成. JVM上的运行时类型的问题在于,由于擦除,因此无法确定泛型类的变量的确切类型.例如,如果您有一个列表,则无法在运行时确定该列表的通用类型,即无法区分List<String>
和List<Throwable>
.
Types (represented by KType
in kotlin-reflect
) usually come from signatures of declarations in your code; they denote a broad set of values which functions take as parameters or return. A type consists of the class, generic arguments to that class, and nullability. The problem with types at runtime on JVM is that because of erasure, it's impossible to determine the exact type of a variable of a generic class. For example if you have a list, you cannot determine the generic type of that list at runtime, i.e. you cannot differentiate between List<String>
and List<Throwable>
.
不过,要回答您的第一个问题,您可以使用createType()
在KClass
中创建一个KType
:
To answer your initial question though, you can create a KType
out of a KClass
with createType()
:
val type: KType = Any::class.createType()
请注意,如果类是泛型的,则需要传递泛型参数的类型投影.在简单情况下(所有类型变量都可以用星状投影代替),starProjectedType
也将起作用.有关createType
和starProjectedType
的更多信息,请参阅此答案.
Note that if the class is generic, you need to pass type projections of generic arguments. In simple cases (all type variables can be replaced with star projections), starProjectedType
will also work. For more info on createType
and starProjectedType
, see this answer.
这篇关于如何在Kotlin中获取KType?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!