对Java通用方法类型推断的困惑 [英] Confusion over Java generic method type inference

查看:81
本文介绍了对Java通用方法类型推断的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例方法如下:

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.只要您传递的类型与声明一致,代码就应该编译;在您的情况下,ObjectString的列表与声明一致.

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.classObject.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

关于ideone的演示.

这篇关于对Java通用方法类型推断的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆