最近我重构代码时遇到了这个问题:
下面的"getList()"方法具有参数化返回类型。在此之后,我放置了三个尝试将<T>
隐式绑定到<Integer>
的方法。
我无法弄清楚的是,为什么前两个编译并且正确运行,而第三个(bindViaMethodInvocation)甚至无法编译。
有任何线索吗?
在StackOverflow上寻找类似的问题时,我找到了这个问题:Inferred wildcard generics in return type。那里的答案(由Laurence Gonsalves提供)有一些有用的参考链接来解释应该发生的事情: "问题在于(就像您所提供的那样),编译器正在执行Capture Conversion。我相信这是由于JLS的§15.12.2.6所致。"
package stackoverflow;
import java.util.*;
public class ParameterizedReturn
{
// Parameterized method
public static <T extends Object> List<T> getList()
{
return new ArrayList<T>();
}
public static List<Integer> bindViaReturnStatement()
{
return getList();
}
public static List<Integer> bindViaVariableAssignment()
{
List<Integer> intList = getList();
return intList;
}
public static List<Integer> bindViaMethodInvocation()
{
// Compile error here
return echo(getList());
}
public static List<Integer> echo(List<Integer> intList)
{
return intList;
}
}