Type Witness in java generics

I understand what the Witness type is, as I see from the Generics Trail In Java Documentation

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

Alternatively, if you omit the type witness, the Java compiler automatically infers (from the method arguments) that the type is an Integer parameter:

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

I would like to understand

  • What is the right way to do this? Use Witness Witnesses or allow Java to output?
  • Is there a case where the use of a type witness is absolutely necessary?
  • Is this a Java 5 feature or added later?
+6
source share
3 answers

A few quick answers to your questions:

How to do it right? Using Type Witness or letting Java output?

, . . . , . .


, ?

. , . , , . .


Java 5 ?

Java 5 on. - , Java (JLS). Java 8 JLS . Java . , Java 7 Diamond. , Java 5 .

+10

   , ?

Java 5 ?

, Java SE 8

Generics Trail Java:

, processStringList . Java SE 7 :

processStringList(Collections.emptyList());

Java SE 7 , :

List<Object> cannot be converted to List<String> The compiler requires

T, Object. , Collections.emptyList List, processStringList. , Java SE 7 :

processStringList(Collections.<String>emptyList());

Java SE 8. , , processStringList. , processStringList List. Collections.emptyList List, List, , T . , Java SE 8 :

processStringList(Collections.emptyList());
+4

, Java 5. JLS Third Edition, Java 5 6:

8.8.7.1

ExplicitConstructorInvocation:
    NonWildTypeArgumentsopt this ( ArgumentListopt ) ;
    NonWildTypeArgumentsopt super ( ArgumentListopt ) ;
    Primary. NonWildTypeArgumentsopt super ( ArgumentListopt ) ; 

NonWildTypeArguments:
    < ReferenceTypeList >

ReferenceTypeList: 
    ReferenceType
    ReferenceTypeList , ReferenceType

15.12

MethodInvocation:
    MethodName ( ArgumentListopt )
    Primary . NonWildTypeArgumentsopt Identifier ( ArgumentListopt )
    super . NonWildTypeArgumentsopt Identifier ( ArgumentListopt )
    ClassName . super . NonWildTypeArgumentsopt Identifier ( ArgumentListopt )
    TypeName . NonWildTypeArguments Identifier ( ArgumentListopt )

Please note that they are called NonWildTypeArguments. The term Type Witness does not appear in JLS. In JLS SE 8, call specifications are rewritten to use a preexisting concept TypeArguments; and the word "witness" is still missing.

( MethodNamealready includes TypeName.Identifier, so the fifth method call defines the explicit use of the Type Witness, so it is not marked as optional.)

+1
source

All Articles