从通用类型获取 Moshi 适配器 - Kotlin

Get Moshi adapter from a generic Type - Kotlin

我正在尝试设置一个 Moshi 适配器,以便我可以获得作为通用传递的任何模型。到目前为止,我在从 T generic 获取 class 时遇到问题,IDE 说 Cannot use T as a reified type parameter. Use a class instead

有什么解决办法吗?

val model = getModel<SimpleModel>()    

private fun <T> getModel() : T? {
  val moshi = Moshi.Builder().build()
  val adapter = moshi.adapter<T>(T::class.java)
  return adapter.fromJson("{\"name\": \"this_guy\"}")
}

谢谢!

使用 private inline fun <reified T> getModel(): T 作为函数声明。

将类型参数声明为具体化允许您访问其 class 对象。