相关疑难解决方法(0)

如何在Kotlin中获取泛型参数类

Firebase snapshot.getValue()预计会被调用如下:

snapshot?.getValue(Person::class.java)
Run Code Online (Sandbox Code Playgroud)

但是我想Person用通过类声明传递给类的泛型参数替换,即

class DataQuery<T : IModel> 
Run Code Online (Sandbox Code Playgroud)

并使用该泛型参数执行以下操作:

snapshot?.getValue(T::class.java)
Run Code Online (Sandbox Code Playgroud)

但当我尝试我得到一个错误说明

只有类可以在类文字的左侧使用

是否可以像在C#中那样为泛型参数提供类约束,或者是否可以使用其他语法来获取泛型参数的类型信息?

kotlin

48
推荐指数
4
解决办法
3万
查看次数

Kotlin 获取没有实例的泛型类的类型

嘿,想要获取T 的类型,但我无法从实例中获取它,我必须从类参数中获取它,该怎么做?

abstract class ViewModelFragment<T : ViewModel>{
    protected lateinit var mViewModel: T

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       mViewModel = ViewModelProviders
                    .of(scope)
                    .get(getGenericTClass())
    // .get(mViewModel.javaClass) // not working either

   }

   inline fun<reified R> getGenericTClass() = R::class.java

}
Run Code Online (Sandbox Code Playgroud)

现在编译器抱怨

不能使用“T”作为精炼的类类型。请改用 Class。

我尝试使用以下解决方案:https : //stackoverflow.com/a/34463352/2163045但对我不起作用

kotlin-extension

6
推荐指数
1
解决办法
1205
查看次数

标签 统计

kotlin ×1

kotlin-extension ×1