对Java通用方法类型推断的困惑 [英] Confusion over Java generic method type inference
问题描述
示例方法如下:
static <T> void doSomething(List<? super T> list1, List<? extends T> list2) { }
我想知道在这种情况下将通过哪种逻辑来推断什么类型.假设我正在这样调用此方法:
I am wondering what type will be inferred in this situation and by what logic. Let's say I am calling this method like this:
doSomething(new ArrayList<Object>(), new ArrayList<String>());
T 类型的计算结果是否为 Object 或 String ?
Would T type evaluate as Object or String?
推荐答案
此调用不会将T
绑定到特定类.由于泛型的类型擦除实现,Java不需要知道确切的T
.只要您传递的类型与声明一致,代码就应该编译;在您的情况下,Object
和String
的列表与声明一致.
This call does not bind T
to a specific class. Java does not need to know the exact T
because of type erasure implementation of the generics. As long as the types that you pass are consistent with the declaration, the code should compile; in your case, lists of Object
and String
are consistent with the declaration.
让我们稍微扩展一下代码,以便我们可以强制将T
绑定到特定类型.也许最简单的方法是通过Class<T>
,如下所示:
Let's expand your code a little so that we could force binding of T
to a specific type. Perhaps the easiest way to do it is to pass Class<T>
, like this:
static <T> void doSomething(List<? super T> list1, List<? extends T> list2, Class<T> cl) {
System.out.println(cl);
}
现在让我们尝试使用String.class
和Object.class
调用doSomething
:
Now let us try calling doSomething
with String.class
and with Object.class
:
doSomething(new ArrayList<Object>(), new ArrayList<String>(), Object.class);
doSomething(new ArrayList<Object>(), new ArrayList<String>(), String.class);
两个调用均成功编译,产生输出
Both calls successfully compile, producing the output
class java.lang.Object
class java.lang.String
这篇关于对Java通用方法类型推断的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!