如何从kPalin中的KParameter获取类的引用?
下面的代码是关于反射。 它试图做2件事情:
-
case1()
从SimpleStudent
类创建一个实例,它的工作原理。 -
case2()
从Student
类创建一个实例,不工作。
case2()
不能正常工作的原因是在里面的generateValue()
:
- 我不知道如何检查它是kotlin类型或我自己的类型(我有一个肮脏的方式来检查
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() }
问题解决了:
你可以通过使用param.type.classifier as KClass<T>
来获得::class
,其中param is KParameter