Reputation: 2470
Does generic method return type resolve on the basis of value reference? e.g.
public class TestGenericMethod
{
public static void main(String[] args)
{
TestGenericMethod dis = new TestGenericMethod();
String str = dis.getFirst(singletonList("String"));
System.out.println("| String ==> " + str);
Integer in = dis.getFirst(singletonList(5));
System.out.println("| Integer ==> " + in);
}
private <T> T getFirst(List<Object> objs)
{
return (T) objs.get(0);
}
}
Referring the code snippet, This code compiles and runs gracefully. My question here, since I'm not specifically type casting list object to my type, still return type is compatible to both String
and Integer
. So is return type being resolved on the basis of value reference?
Upvotes: 1
Views: 483
Reputation: 1254
As mentioned in other answers the return type is inferred by the compiler from the target variable type. A bit more details what is going on behind the scene.
If check the bytecode of the class, the actual return type of getFirst()
method is Object
.
// signature <T:Ljava/lang/Object;>(Ljava/util/List<Ljava/lang/Object;>;)TT;
private getFirst(Ljava/util/List;)Ljava/lang/Object;
At runtime the JVM checks the actual type of the object returned from getFirst()
and throw ClassCastException if it differ.
INVOKESPECIAL TestGenericMethod.getFirst (Ljava/util/List;)Ljava/lang/Object;
CHECKCAST java/lang/Integer
Upvotes: 1
Reputation: 691765
The return type is inferred by the compiler from the type of the variable that you're assigning the result to (str
, in
).
The actual type of the returned value, of course, will be whatever the type of the first object of the list is, and you could get a ClassCastException at runtime, since your code is not typesafe and you're ignoring the generic cast is unchecked. Try for example
Integer oops = dis.getFirst(singletonList("hello"));
Upvotes: 5
Reputation: 57124
The compiler tries to infer T
and the only place it can infer it from in your situation is by looking at the type of the variable you want to store the returned T
in.
Upvotes: 2