我想创建具有通用参数的对象工厂:
interface Foo<T> {
fun buzz(param: T)
}
我有两个测试实现:
class FooImpl1 : Foo<String> {
override fun buzz(param: String) {
// implementation 1
}
}
class FooImpl2 : Foo<Int> {
override fun buzz(param: Int) {
// implementation 2
}
}
现在我创建了 map 来包含我所有的实现
val implementationMap = mapOf<String, Foo<*>>(
Pair(firstKey, FooImpl1()),
Pair(secKey, FooImpl2())
)
我也有带参数的 map :
val paramMap = mapOf<String, Any>(
Pair(firstKey, "String param"),
Pair(secKey, 12)
)
但是现在当我从我的 map 中获取第一个元素时:
implementationMap.getValue(firstKey).buzz(paramMap.getValue(firstKey))
我的
buzz
方法拒绝任何参数(希望 Nothing
作为类型)所以我创建了另一个类型的 map
val classMap = mapOf<String, KClass<*>>(
Pair(firstKey, FooImpl1::class),
Pair(secKey, FooImpl2::class)
)
val paramClassMap = mapOf<String, KClass<*>>(
Pair(firstKey, String::class),
Pair(secKey, Int::class)
)
但我不能这样投:
implementationMap.getValue(firstKey)
.cast < classMap.getValue(firstKey) > () // not possible
.buzz(
paramMap.getValue(firstKey)
.cast < paramClassMap.getValue(firstKey) > () // not possible
)
或者那个
(implementationMap.getValue(firstKey) // FooImpl1
/*not possible */ as classMap.getValue(firstKey)) // (FooImpl1::class)
.buzz(
paramMap.getValue(firstKey) // String
/*not possible */ as paramClassMap.getValue(firstKey)) // (String::class)
我也尝试使用
Token
输入,但它无济于事:val classMap = mapOf<String, Type>(
Pair(firstKey, object: TypeToken<FooImpl1>() {}.type),
Pair(secKey, object: TypeToken<FooImpl1>() {}.type)
)
任何想法如何正确地转换它?还是一些“不同的方法”的想法?
最佳答案
恐怕你只需要做一些未经检查的类型转换。
interface Foo<T> {
fun buzz(param: T)
}
class FooImpl1 : Foo<String> {
override fun buzz(param: String) {
println(param)
}
}
class FooImpl2 : Foo<Int> {
override fun buzz(param: Int) {
println(param)
}
}
val implementationMap = mapOf<String, Foo<*>>(
Pair("firstKey", FooImpl1()),
Pair("secKey", FooImpl2())
)
val paramMap = mapOf<String, Any>(
Pair("firstKey", "String param"),
Pair("secKey", 12)
)
fun main() {
@Suppress("UNCHECKED_CAST")
val imp = implementationMap["firstKey"] as Foo<Any?>
val param = paramMap["firstKey"]
imp.buzz(param)
}
关于generics - Kotlin 通用工厂动态转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55606111/