如何访问generics类参数中的属性/方法

来自C#的Kotlin新手。

我想创建一个类,通过generics需要一个可互换的类对象。 在类中,我想访问类中的属性值和调用方法。 我认为这必须通过某种反思机制。 挖掘Kotlin引用我一直在尝试应用建议到我的代码,但是我得到一些神秘的错误。

任何帮助表示赞赏。

Error:(35, 20) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: @InlineOnly public operator inline fun  Lazy.getValue(thisRef: Any?, property: KProperty): T1? defined in kotlin @InlineOnly public operator inline fun  Map.getValue(thisRef: Any?, property: KProperty): T1? defined in kotlin.collections @SinceKotlin public fun  Map<Class, T1?>.getValue(key: Class): T1? defined in kotlin.collections @JvmName @InlineOnly public operator inline fun  MutableMap.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  KClass.memberProperties: Collection<KProperty1> is not satisfied: inferred type CapturedTypeConstructor(out T1?) is not a subtype of Any open class Base (@Autowired var t2: T2) { @Autowired var request: T1? = null inline fun  retrieveClass(): T1? { return request.getValue(T1::class.java) } fun endpoint( @ApiParam(value = "Options", required = true) @Valid @RequestBody body: T1 ): ResponseEntity { type1 = body val obj = retrieveClass() for (prop in obj::class.memberProperties) { println("${prop.name} = ${prop.get(obj)}") } val usefulResult = obj.usefulMethod() } } 

在修改访问generics类属性后,代码如下所示,在println中有一个错误:

 Error:(82, 56) Kotlin: Out-projected type 'KProperty1' prohibits the use of 'public abstract fun get(receiver: T): R defined in kotlin.reflect.KProperty1' open class Base (@Autowired var t2: T2) { @Autowired var request: T1? = null fun endpoint( @ApiParam(value = "Options", required = true) @Valid @RequestBody body: T1 ): ResponseEntity { val myClass = body.let { it::class } val my2ndClass = t2.let { it::class } for (prop in myClass.memberProperties) { println("${prop.name} = ${prop.get(myClass)}") } val usefulResult = my2ndClass.usefulMethod(myClass) } }