I have a generic method like below
private fun <T> getSomething(): T {
return "something" as T
}
How can I call this method with a variable T
type?
val types = arrayListOf<Type>(String::class.java, Boolean::class.java)
types.forEach { type ->
val something = getSomething<type>() // Unresolved reference: type
}
在运行时,我不知道什么是泛型类型T
.我从types
中获取类型,应该使用泛型getSomething
方法传递它.
Use case
我想调用有几个表的数据库.示例模型如下
class User{
}
class Student{
}
Since all the calling queries are basically same, I want to have generic method for calling database and get data.
private fun <T> getData(model: String): List<T>?{
return when(model){
"user" -> getUsers()
"student" -> getStudents()
else -> null
}
}
So when I call above method. Within my loop I want to pass Type
as either User
or Student
.
val types = arrayListOf<Type>(User::class.java, Student::class.java)
types.forEach { type ->
val data = getData<type>(type.javaClass.simpleName) // Unresolved reference: type in <type>
}
How can I achieve it.