如何在kotlin中从KParameter获取类引用?

时间:2017-10-02 01:55:51

标签: reflection kotlin

以下代码是关于反思的。 它试图做两件事:

  1. case1()SimpleStudent类创建一个实例,它可以正常工作。
  2. case2()Student类创建一个实例,而不是工作。
  3. case2()无法解决问题的原因在于generateValue()

    1. 我不知道怎么检查它是kotlin类型还是我自己的类型(我有一种肮脏的方式来检查param.type.toString() not contain "kotlin"但我想知道是否有更好的解决方案
    2. 当它是自定义类时,我不知道如何获取它的类引用。问题在于即使param.type.toString() == "Lesson",当我尝试获取param.type::class时,它是class kotlin.reflect.jvm.internal.KTypeImpl
    3. 那么,如何解决呢?感谢

      ==============

      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()
      }
      

1 个答案:

答案 0 :(得分:1)

问题解决了:

您可以::class使用param.type.classifier as KClass<T>

来获取param is KParameter