Type Witness in java generics

前端 未结 3 882
忘了有多久
忘了有多久 2020-12-31 17:11

I understand what Type Witness is as I see from Generics Trail In Java Documentation

BoxDemo.addBox(Integer.valueOf(10), listOfIntegerBoxes);
         


        
3条回答
  •  无人及你
    2020-12-31 18:00

    Is there a case where using type witness is absolutely needed?

    Is this a feature from Java 5 or added later?

    Example below shows mandatory case of using type witness and improvements that came in Java SE 8

    Quote from the Generics trail Java documentation:

    Suppose you want to invoke the method processStringList with an empty list. In Java SE 7, the following statement does not compile:

    processStringList(Collections.emptyList());
    

    The Java SE 7 compiler generates an error message similar to the following:

    List cannot be converted to List The compiler requires
    
      
      

    a value for the type argument T so it starts with the value Object. Consequently, the invocation of Collections.emptyList returns a value of type List, which is incompatible with the method processStringList. Thus, in Java SE 7, you must specify the value of the value of the type argument as follows:

    processStringList(Collections.emptyList());
    

    This is no longer necessary in Java SE 8. The notion of what is a target type has been expanded to include method arguments, such as the argument to the method processStringList. In this case, processStringList requires an argument of type List. The method Collections.emptyList returns a value of List, so using the target type of List, the compiler infers that the type argument T has a value of String. Thus, in Java SE 8, the following statement compiles:

    processStringList(Collections.emptyList());
    

    提交回复
    热议问题