【问题标题】:Kotlin Generic Reflection SubclassKotlin 通用反射子类
【发布时间】:2019-03-09 01:50:56
【问题描述】:

我有一个接受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

【问题讨论】:

    标签: java generics kotlin covariance


    【解决方案1】:

    您必须使用方差: fun testStuff(type: Class&lt;out Bag&lt;Int&gt;&gt;)

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

    【讨论】:

      【解决方案2】:

      Bag&lt;Int&gt;IntBag 实际上不同,因为它们是不同的类。

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

      typealias IntBag = Bag<Int>
      

      【讨论】:

        【解决方案3】:

        但是如果我将类型转换为它的超类型,它运行良好(带有警告)。

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

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

        由于类型擦除,Class&lt;String&gt; 可以转换为 Class&lt;Anything&gt;,这也适用于其他泛型类型。但实际上,IntBag::class.javaClass&lt;IntBag&gt;不是Class&lt;Bag&lt;Int&gt;&gt;

        事实上,Class&lt;Bag&lt;Int&gt;&gt; 类型的值是不存在的;如果你想要Class&lt;any subtype of Bag&lt;Int&gt;&gt;,那么 Pamela Hill 的回答给出了语法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多