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

时间:2018-01-18 17:00:51

标签: oop kotlin

我有一个关于在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
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!
    }
}

感谢您提出任何建议

1 个答案:

答案 0 :(得分:0)

您应该可以使用castsafeCast

    jdbc:derby://localhost:1527/macdb;create=true 

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

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

func.call(bundleClass.cast(bundle))