Gangmax Blog

Java Type Inference

From here.

Please read the following Java code, which can be compiled and executed without any issue(with JDK 7+).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.junit.jupiter.api.Test;

public class TypeParameterTest {
public static <T, X> T read(X test) {
return null;
}

@Test
public void test() {
String a = TypeParameterTest.read("");
String b = TypeParameterTest.read(123);
Integer c = TypeParameterTest.read("");
Integer d = TypeParameterTest.read(123);
}
}

Notes

  1. The “read” method has 2 type parameters, one for argument and another for return value.

  2. In the “test” method, 4 invocations of the “read” method have different argument types and return value types. The magic part is that, all of them can be compiled successfully. It means the “read” method can return different types in different circumstances, depending on where it’s invoked. This happens to the method argument as well.

  3. The reason is that, the Java compiler has an ability called “type inference” which is used “to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments“(from here).

I noticed this when I was reading how to use the “JsonPath“ library here, and was astonished when I found the “read” method could return different types in different situations.

The full “Generics“ tutorial is also worth reading.

Comments