Kotlin:将类的实例转换为动态types

我有一个关于在Kotlin铸造的问题。 我想要通过解析JSON来生成一个对象。 它应该被投射的types将被动态地确定。 这是我在下面的一段代码的评论中解释的问题:

// interface for objects that are received as json interface Bundle // many data classes implementing the Bundle interface // eg data class DailyPostBundle(/* ... */) : Bundle data class CreatePostBundle(/* ... */ : Bundle // ... val data = /*json string representing a Bundle*/ // logic: // does this function have to @Operator annotation? func.findAnnotation()?.let { // yes it does. is it the right operator? if (it.operatorName == operator) { // yes it is // find the data bundle class from class path val bundleClass = Class.forName("$bundleClassesPackage.${type}Bundle") // now create an instance of the class from the json string val bundle = Gson().fromJson(data, bundleClass) // bundle is correctly parsed, BUT: it is of type  // I want to pass it to the function, // therefore it needs to have a type that is an implementation of Bundle, // eg DailyPostBundle // I cannot cast it explicitly here, the type to which bundle should be cast should be inferred from bundleClass // using the dynamically located class works for parsing JSON, but it does not work for casting func.call(bundle) // doesnt work! // what I want to do (pseudo-code): func.call(bundle as bundleClass) // doesnt compile! } } 

谢谢你的任何建议

你应该可以使用cast或safeCast 。

 func.call(bundleClass.cast(bundle)) 

(更新)其实,你得到一个Java类对象,所以正确的文档在这里 。

此外,要使用Kotlin的safeCast,您需要获得Kotlin类的实例:

 bundleClass.kotlin