Java Kotlin泛型反射子类

Java Kotlin泛型反射子类,java,generics,kotlin,covariance,Java,Generics,Kotlin,Covariance,我有一个接受类的函数。 当我传递该GenericType的子类时,编译器错误会显示以下消息: 类型推断失败。预期类型不匹配 但是,如果我将类型强制转换为它的超类型,它运行良好(带有警告)。如何做到这一点而不铸造 open class Bag<T> class IntBag: Bag<Int>() fun testStuff(type: Class<Bag<Int>>) { // Do stuff } testStuff(IntBag:

我有一个接受
类的函数。
当我传递该
GenericType
的子类时,编译器错误会显示以下消息:
类型推断失败。预期类型不匹配

但是,如果我将类型强制转换为它的超类型,它运行良好(带有警告)。如何做到这一点而不铸造

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
openclass包
类IntBag:Bag()
有趣的testStuff(类型:Class){
//做事
}
testStuff(IntBag::class.java)//这不会编译
testStuff(IntBag::class.java作为类)//编译时会出现警告,但运行正常

您必须使用方差:
fun testStuff(类型:Class)

Bag
实际上与
IntBag
不同,因为它们是不同的类

您可以将typealias用于
IntBag
,如下所示:

typealias IntBag = Bag<Int>
typealias IntBag=Bag
但是如果我将类型强制转换为它的超类型,它运行良好(带有警告)

如果您这样做,它也会“运行良好”(取决于
testStuff
的内部结构)

testStuff(String::class.java as Class<Bag<Int>>)
testStuff(String::class.java作为类)
由于类型擦除,可以将
强制转换为
,这也适用于其他泛型类型。但是实际上,
IntBag::class.java
是一个
,而不是

事实上,没有类型为
Class
的值;如果你想要
,那么帕梅拉·希尔的答案给出了语法