Where does this Java function derive its generic type?

I found some general code and it made me understand how this works. I donโ€™t understand where it gets the generic type that is used for T. This is a simplified example, but I still donโ€™t understand how this is valid Java code.

public static void main(String[] args) { System.out.print(get()); } public static <T> T get() { return (T) getObj(); } public static Object getObj() { return Boolean.FALSE; } 
+6
source share
2 answers

Type inference is based on callsite.

However, type inference only applies to return types if the return value is assigned to a variable. It is written in spec

If the result of a method arises in the context where it will undergo an assignment transformation, then [...]

Otherwise, any parameters of an unresolved type always become Object .
In your example, this will work because there is an overload of print(Object) .

On the other hand, look at this code:

 print(get()); public void print(Boolean x) { } public <T> T get() { return (T) Boolean.FALSE; } 

This will give a compilation error because the compiler prints get() as returning Object before looking at print() .

+3
source

In the code you wrote, T is not tied to anything. Java will assign a type T whenever you call the get method, and it will look at the type you expect to get ... but this seems to work only if you explicitly declare which type you expect. Take a look at the following example:

 public static void jump(String a) { } public static <T> T get() { return (T) null; } public static void main(String[] args) { //This works quite well, generic parameter T is inferred to be String String blah = get(); jump(blah); } 

On the other hand,

 public static void jump(String a) { } public static <T> T get() { return (T) null; } public static void main(String[] args) { //This doesn't work, Java does not bind T to anything hence Object is used... and no jump for object is found jump(get()); } 

At least that's how it works in Java 6.

+1
source

All Articles