Skip to main content

Java Type Witness Generic

Ayman Patel

Ayman Patel

Back End Engineer @ Mastercard

Links

  • Type Witness
List<String> moons = Collections.emptyList();

This statement expects to receive an instance of List<String> which is the target type. Because emptyList() returns List<T>, the compiler infers that type argument T must be String. Java 7 and Java 8 support this inference. Alternatively, you could employ a type witness and specify T's value as shown below:

List<String> moons = Collections.<String>emptyList(); // Type witness not need from Java 8

Another example:

Planet(String name, List<String> moons)
{
this.name = name;
this.moons = moons;
}
Planet mercury = new Planet("Mercury", Collections.emptyList()); // compile error under Java 7,
// which outputs an error message that's similar to the following message:List<Object> cannot be converted to List<String>