How to get property values in generic class through reflection

I get below cryptic error on the .get(myClass) call

Kotlin: Out-projected type ‘KProperty1<out T1, Any?>’ prohibits the use of ‘public abstract fun get(receiver: T): R defined in kotlin.reflect.KProperty1’

when trying to compile the following code

    open class Base<T1 : Any, T2 : Any> (@Autowired var t2: T2) {

        @Autowired var request: T1? = null

      fun endpoint(
        @ApiParam(value = "Options", required = true) @Valid @RequestBody
            body: T1
        ): ResponseEntity<MyResponse> {
            val myClass  = body.let { it::class }
            val my2ndClass  = t2.let { it::class }

           val parameters = Parameters()

           parameters.contextId = myClass.memberProperties.find { it.name == "contextId" }?.get(myClass) as String

           val function = t2.memberFunctions.find { it.name == "getViewModel" }
           val vm: Model = function?.call(parameters, span) as Model
      }
    }

At this point I am a little lost as to what is wrong other than there may be a type mismatch somewhere. It could be nice if the error precisely described what exactly is wrong and possibly suggest a fix

1 Like

I just hit this as well.

Why should this be prohibited?

What is the right way to read a KProperty generically?

Actually, the class doesn’t have to be generic to have this problem.

I hit this problem trying to read properties when I know neither their names nor their types.

The problem is simply: how to read a property through reflection?

1 Like