mercredi 22 novembre 2017

How to access attributes/methods in generic class parameter

New to Kotlin coming from C#.

I am trying create a class that takes in an interchangeable class object through generics. In the class I would like to access attribute values and call methods in the class. I assume this has to be through some kind of reflection mechanism. Digging through Kotlin references I have been trying to apply suggestions to my code, however I get some cryptic errors.

Any help is appreciated.

Error:(35, 20) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
@InlineOnly public operator inline fun <T> Lazy<T1?>.getValue(thisRef: Any?, property: KProperty<*>): T1? defined in kotlin
@InlineOnly public operator inline fun <V, V1 : T1?> Map<in String, T1?>.getValue(thisRef: Any?, property: KProperty<*>): T1? defined in kotlin.collections
@SinceKotlin public fun <K, V> Map<Class<T1>, T1?>.getValue(key: Class<T1>): T1? defined in kotlin.collections
@JvmName @InlineOnly public operator inline fun <V> MutableMap<in String, in T1?>.getValue(thisRef: Any?, property: KProperty<*>): T1? defined in kotlin.collections
Error:(75, 20) Kotlin: Expression in a class literal has a nullable type 'T1?', use !! to make the type non-nullable
Error:(75, 35) Kotlin: Type parameter bound for T in val <T : Any> KClass<T>.memberProperties: Collection<KProperty1<T, *>>
 is not satisfied: inferred type CapturedTypeConstructor(out T1?) is not a subtype of Any

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

    @Autowired var request: T1? = null

  inline fun <reified T1: Any> retrieveClass(): T1? {
    return request.getValue(T1::class.java)
  }

  fun endpoint(
    @ApiParam(value = "Options", required = true) @Valid @RequestBody
        body: T1
    ): ResponseEntity<MyResponse> {
        type1 = body
        val obj = retrieveClass()
        for (prop in obj::class.memberProperties) {
           println("${prop.name} = ${prop.get(obj)}")
        }
        val usefulResult = obj.usefulMethod()
    }
}





Aucun commentaire:

Enregistrer un commentaire