方法调用如何进行类型推断? [英] How type inference work for method calls?
问题描述
请考虑以下示例:
public class Learn {
public static <T> T test (T a, T b) {
System.out.println(a.getClass().getSimpleName());
System.out.println(b.getClass().getSimpleName());
b = a;
return a;
}
public static void main (String[] args) {
test("", new ArrayList<Integer>());
}
}
在main
方法中,我使用String
和ArrayList <Integer>
对象调用test
.两者都是不同的东西,通常将ArrayList
分配给String
会产生编译错误.
In the main
method, I am calling test
with a String
and an ArrayList <Integer>
object. Both are different things and assigning an ArrayList
to String
(generally) gives a compile error.
String aString = new ArrayList <Integer> (); // won't compile
但是我正是在test
的第三行中这样做,程序可以编译并运行良好.首先,我认为类型参数T
被替换为同时与String
和ArrayList
兼容的类型(如Serializable
).但是test
中的两个println
语句分别将"String"和"ArrayList"打印为a
和b
的类型.我的问题是,如果在运行时a
是String
而b
是ArrayList
,我们如何将a
分配给b
.
But I am doing exactly that in the 3rd line of test
and the program compiles and runs fine. First I thought that the type parameter T
is replaced by a type that's compatible with both String
and ArrayList
(like Serializable
). But the two println
statements inside test
print "String" and "ArrayList" as types of a
and b
respectively. My question is, if a
is String
and b
is ArrayList
at runtime, how can we assign a
to b
.
推荐答案
For a generic method, the Java compiler will infer the most specific common type for both parameters a
and b
.
推理算法确定参数的类型,以及确定结果是否被分配或返回的类型(如果可用).最后,推理算法会尝试找到最适合所有参数的特定类型.
您没有将对test
的调用结果分配给任何对象,因此没有目标可以影响推断.
You aren't assigning the result of the call to test
to anything, so there is no target to influence the inference.
在这种情况下,即使String
和ArrayList<Integer>
都有一个通用的超类型Serializable
,所以T
被推断为Serializable
,并且您始终可以将一个相同类型的变量分配给另一个.对于其他示例,您甚至可能会找到Object
作为常见超类型.
In this case, even String
and ArrayList<Integer>
have a common supertype, Serializable
, so T
is inferred as Serializable
, and you can always assign one variable of the same type to another. For other examples, you may even find Object
as the common supertype.
但是仅仅因为您有类型为T
的变量被推断为Serializable
,所以对象本身仍然是String
和ArrayList
,因此获取其类并打印其名称仍会打印String
和ArrayList
.您不是在打印变量的类型;而是在打印变量的类型.您正在打印对象的类型.
But just because you have variables of type T
that are inferred as Serializable
, the objects themselves are still a String
and an ArrayList
, so getting their classes and printing their names still prints String
and ArrayList
. You're not printing the type of the variables; you're printing the type of the objects.
这篇关于方法调用如何进行类型推断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!