简体   繁体   English

泛型混淆中的类型擦除

[英]Type erasure in generics confusion

I was reading concept of type erasure in generics. 我正在阅读泛型中类型擦除的概念。 While executing the below piece of code I got confused. 在执行以下代码时,我感到困惑。

public class CollectionsWild {
    void Test(Collection<?> t){
        System.out.println("Collection");
    }

    void Test(List<Integer> t){
        System.out.println("List");
    }


    public static void main(String[] args) {
        CollectionsWild o = new CollectionsWild();
        o.Test(new ArrayList<String>());
    }

}

As per the type erasure concept, " List<Integer> t " is converted to "List t" in bytecode. 根据类型擦除的概念,“ List<Integer> t t”以字节码转换为“ List t”。 So why is my method test called which is having Collection as the parameter. 那么为什么要调用我的方法测试呢?它以Collection为参数。 It should have called the method with List as parameter 它应该已经使用List作为参数调用了方法

This is nothing to do with erasure. 这与擦除无关。 Overload resolution is done at compile time. 重载解析在编译时完成。 Only one overload matches ArrayList<String> and that is the one that is chosen. 只有一个重载与ArrayList<String>匹配,这就是选择的重载。 If there was more than one match, the most specific would have been selected. 如果有多个比赛,则将选择最具体的比赛。

In the case that of overloading with the same type erasure, the definition of the type does not compile before overload resolution is even considered. 在具有相同类型擦除的重载的情况下,甚至在考虑重载解析之前都不会编译类型的定义。

Method selection is a compile-time thing. 方法的选择是编译时的事情。 Type erasure happens afterward . 类型擦除随后发生。 As you can see in JLS§15.12.2 , generic type parameters are considered: 正如您在JLS§15.12.2中看到的那样考虑泛型类型参数:

Deciding whether a method is applicable will, in the case of generic methods (§8.4.4), require an analysis of the type arguments. 在泛型方法(第8.4.4节)的情况下,确定方法是否适用将需要对类型参数进行分析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM