下面的代码是关于反射的。
它尝试做两件事:
case1()
从SimpleStudent
类创建一个实例,它可以工作。 case2()
从Student
类创建一个实例,不起作用。 case2()
与问题不一样的原因是在generateValue()
内部:param.type.toString() not contain "kotlin"
,但我想知道是否有更好的解决方案param.type.toString() == "Lesson"
,当我尝试获取param.type::class
时,它也是class kotlin.reflect.jvm.internal.KTypeImpl
那么,如何解决呢?谢谢
==============
import kotlin.reflect.KParameter
import kotlin.reflect.full.primaryConstructor
import kotlin.test.assertEquals
data class Lesson(val title:String, val length:Int)
data class Student(val name:String, val major:Lesson )
data class SimpleStudent(val name:String, val age:Int )
fun generateValue(param:KParameter, originalValue:Map<*,*>):Any? {
var value = originalValue[param.name]
// if (param.type is not Kotlin type){
// // Get its ::class so that we could create the instance of it, here, I mean Lesson class?
// }
return value
}
fun case1(){
val classDesc = SimpleStudent::class
val constructor = classDesc.primaryConstructor!!
val value = mapOf<Any,Any>(
"name" to "Tom",
"age" to 16
)
val params = constructor.parameters.associateBy (
{it},
{generateValue(it, value)}
)
val result:SimpleStudent = constructor.callBy(params)
assertEquals("Tom", result.name)
assertEquals(16, result.age)
}
fun case2(){
val classDesc = Student::class
val constructor = classDesc.primaryConstructor!!
val value = mapOf<Any,Any>(
"name" to "Tom",
"major" to mapOf<Any,Any>(
"title" to "CS",
"length" to 16
)
)
val params = constructor.parameters.associateBy (
{it},
{generateValue(it, value)}
)
val result:Student = constructor.callBy(params)
assertEquals("Tom", result.name)
assertEquals(Lesson::class, result.major::class)
assertEquals("CS", result.major.title)
}
fun main(args : Array<String>) {
case1()
case2()
}
最佳答案
问题解决了:
您可以通过使用::class
获得该param.type.classifier as KClass<T>
,其中param is KParameter
关于reflection - 如何从kotlin中的KParameter获取类引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46518588/