Kotlin 通用反射子类

Kotlin Generic Reflection Subclass

我有一个接受 Class<GenericType<Constraint>> 的函数。 当我传递 GenericType<Constraint> 的子类时,编译器出错并显示以下消息: Type Inference Failed. Expected Type Mismatch

但是,如果我将类型转换为它的超类型,它运行良好(有警告)。如何在不投射的情况下做到这一点?

open class Bag<T>

class IntBag: Bag<Int>()

fun testStuff(type: Class<Bag<Int>>) {
    // Do stuff
}

testStuff(IntBag::class.java) // This won't compile
testStuff(IntBag::class.java as Class<Bag<Int>>) // This compiles with a warning, but runs fine

您将不得不用完方差: fun testStuff(type: Class<out Bag<Int>>)

https://kotlinlang.org/docs/reference/generics.html

Bag<Int> 实际上不同于 IntBag,因为它们不同 类。

您可以像这样为 IntBag 使用类型别名:

typealias IntBag = Bag<Int>

BUT if I cast the type to it's supertype, it runs fine (with a warning).

嗯,如果你这样做,它也会 "run fine"(取决于 testStuff 的内部结构)

testStuff(String::class.java as Class<Bag<Int>>)

由于类型擦除,Class<String> 可以转换为 Class<Anything>,这也适用于其他泛型类型。但实际上,IntBag::class.java 是一个 Class<IntBag> 不是 一个 Class<Bag<Int>>.

实际上没有Class<Bag<Int>>类型的值;如果你想要 Class<any subtype of Bag<Int>>,那么 Pamela Hill 的回答给出了语法。