Kotlin通用工厂动态铸造

问题描述 投票:1回答:2

我想用通用参数创建对象工厂:

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())
)

我也有params地图:

val paramMap = mapOf<String, Any>(
    Pair(firstKey, "String param"),
    Pair(secKey, 12)
)

但现在当我从地图中获取第一个元素时:

implementationMap.getValue(firstKey).buzz(paramMap.getValue(firstKey))

我的buzz方法拒绝任何参数(希望Nothing作为类型)

所以我创建了另一个带有类型的地图

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类型,但它没有帮助eather:

val classMap = mapOf<String, Type>(
    Pair(firstKey, object: TypeToken<FooImpl1>() {}.type),
    Pair(secKey, object: TypeToken<FooImpl1>() {}.type)
)

任何想法如何正确施放?还是一些“不同方法”的想法?

generics kotlin casting factory
2个回答
3
投票

你恐怕只需要做一些不受控制的演员。

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)
}

0
投票

好吧,如果你可以将它们组合在一起......

class FooWithParam<T>(foo: Foo<T>, param: T) {
    fun doBuzz() = foo.buzz(param)
}

val fooWithParamMap = mapOf<String, FooWithParam<*>>(
    Pair(firstKey, FooWithParam(FooImpl1(), "String param"),
    Pair(secKey, FooWithParam(FooImpl2(), 12))
)

implementationMap[firstKey].doBuzz()
© www.soinside.com 2019 - 2024. All rights reserved.