How is the generic type getting inferred here?

后端 未结 3 443
一整个雨季
一整个雨季 2021-01-18 00:23
public static void main(String[] args) {
    Map>> map = getHashMap();
}

static  Map getHashM         


        
3条回答
  •  温柔的废话
    2021-01-18 00:50

    At the bytecode level the method will have a descriptor that just says, there's a method with the name getHashMap, that takes no arguments and returns a Map (no generics).

    Then when the compiler is analyzing the line Map>> map = getHashMap();, and it will say, ok, I need to have a variable with a declared type of Map>>, but to actually get the instance I need to call a method. At this point it's the compiler's job to check if the return type of the method matches the declared type of the variable your assigning that result to. So it checks if String matches K, and if Map> matches V, which they do, so it considers that the assignment is type safe, and generates the bytecode which basically uses a Map (no generics) variable.

    If you would have declared your method as:

    static  Map getHashMap()
    {
        return new HashMap();
    }
    

    when analyzing the assignment, the compiler would see that String doesn't match K extends Number, would throw a compilation error, and won't create bytecode for that assignment.

提交回复
热议问题