Oop Kotlin:将类的实例强制转换为动态类型

Oop Kotlin:将类的实例强制转换为动态类型,oop,kotlin,Oop,Kotlin,我有一个关于科特林的问题。我想强制转换一个通过解析JSON生成的对象。应将其转换为的类型将动态确定。这导致了我在下面代码的注释中解释的问题: // interface for objects that are received as json interface Bundle // many data classes implementing the Bundle interface // e.g. data class DailyPostBundle(/* ... */) : Bundle

我有一个关于科特林的问题。我想强制转换一个通过解析JSON生成的对象。应将其转换为的类型将动态确定。这导致了我在下面代码的注释中解释的问题:

// interface for objects that are received as json
interface Bundle

// many data classes implementing the Bundle interface
// e.g.
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<Operator>()?.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 <Any!>
        // I want to pass it to the function, 
        // therefore it needs to have a type that is an implementation of Bundle, 
        // e.g. 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!
    }
}
//作为json接收的对象的接口
接口包
//实现Bundle接口的许多数据类
//例如。
数据类DailyPostBundle(/*…*/):Bundle
数据类CreatePostBundle(/*…*/:Bundle)
// ...
val data=/*表示捆绑包的json字符串*/
//逻辑:
//此函数是否必须添加@Operator注释?
func.findAnnotation()?.let{
//是的。是接线员吗?
if(it.operatorName==运算符){
//是的
//从类路径中查找数据包类
val bundleClass=Class.forName($bundleclassepackage.${type}Bundle)
//现在从json字符串创建该类的实例
val bundle=Gson().fromJson(数据,bundleClass)
//捆绑包已正确解析,但:它的类型为
//我想把它传递给函数,
//因此,它需要有一个类型作为Bundle的实现,
//例如DailyPostBundle
//我不能在这里显式地强制转换它,应该从bundleClass中推断bundle应该被转换到的类型
//使用动态定位的类可以解析JSON,但不能用于强制转换
func.call(bundle)//不起作用!
//我想做什么(伪代码):
func.call(捆绑为bundleClass)//不编译!
}
}
感谢您的建议

您应该能够使用或


(更新)实际上,您得到了一个Java类对象,因此正确的文档是

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

bundleClass.kotlin
bundleClass.kotlin