我有一个关于在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!
}
}
感谢您提出任何建议