我最近在重构代码时遇到了这个问题:参数化方法如何在某些情况下隐式约束而不是其他情况?
下面的方法“getList()”有一个参数化的返回类型。在此之下,我已经提出了三种尝试隐含地将<T>
绑定到<Integer>
的方法。
我不明白为什么前两个编译和运行正确,而第三个(bindViaMethodInvocation)甚至不会编译。
任何线索?
在寻找StackOverflow的类似问题时,我遇到了这个问题: Inferred wildcard generics in return type。答案在那里(信用Laurence Gonsalves)有几个有用的参考链接来解释应该怎么做: “这里的问题(如你所建议的)是编译器执行Capture Conversion。我相信这是一个结果JLS的§15.12.2.6 of the JLS。“或者赋值List<Integer>
或从返回List<Integer>
方法返回语句 -
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;
}
}
谢谢马特!我想我没有正确地对这些做减价。 – 2011-04-05 14:40:00