Kotlin - 在运行时确定嵌套的泛型类型

马修·莱顿

我的解决方案中有以下课程

open class State<T : Any> { ... }

class CustomState : State<BigDecimal> { ... }

abstract class FindState<T : State<*>> { ... }

class FindStateImpl<T : State<*>> : FindState<T>() { ... }

FindState 可以这样称呼

val strState = FindStateImpl<State<String>>(...)

val intState = FindStateImpl<State<Int>>(...)

val customState = FindStateImpl<CustomState>(...)

FindState我需要能够在运行时内部获取以下类类型:

  • TFindState<T : State<*>>这将是State或它们的衍生物。
  • TState

因此对于上面的例子,我需要获得:

val strState = FindStateImpl<State<String>>(...)
//State::class.java
//String::class.java

val intState = FindStateImpl<State<Int>>(...)
//State::class.java
//Int::class.java

val customState = FindStateImpl<CustomState>(...)
//CustomState::class.java
//BigDecimal::class.java (since string is the underlying type T)

到目前为止,我已经有了这样的东西,但它很可怕并且不能完全正常工作:

val stateType = javaClass.kotlin.supertypes[0].arguments[0].type?.jvmErasure?.javaObjectType

是否可以在运行时获取这些类型?

基斯凯

您提供的代码根本不包含所需的类型信息,因为它将被删除。只有将特定类型指定为超类型一部分的子类型才可用。

使用 kotlin 有两种方法可以检索类型信息:

  1. 使用类似于 Guava 的模式TypeToken,并确保提供包含所需类型信息的匿名对象。这将使反射代码工作。
  2. 使用 reified 方法和在编译期间typeOf<T>()嵌入的方法KType
inline fun <reified T : Any, CS : State<T>> FindStateEmbedType(state: CS): FindState<CS> {
    val contentType = typeOf<T>();
    // Do what you need to do with T, perhaps embed in a wrapper FindState type
    return FindStateImplWithType(state, contentType)
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章