java – 参数化方法如何在某些情况下隐式绑定而不是其他情况?

我最近在重构代码时遇到了这个问题:

下面的方法“getList()”具有参数化的返回类型.在此之下,我已经设置了三种尝试隐式绑定< T>的方法.到<整数>.

我无法弄清楚为什么前两个编译和运行正确,而第三个(bindViaMethodInvocation)甚至不会编译.

有线索吗?

在StackOverflow上寻找类似的问题时,我遇到了这个问题:
Inferred wildcard generics in return type.那里的答案(信用证Laurence Gonsalves)有几个有用的参考链接来解释应该发生的事情:
“这里的问题(正如你的建议)是编译器正在执行Capture Conversion.我相信这是JLS §15.12.2.6 of the JLS的结果.”

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;
    }
}
前两个方法在分配转换的上下文中使用getList() – 对List< Integer>的赋值.或返回List< Integer>的方法的return语句.对于bindViaMethodInvocation也是如此 – 使用表达式作为方法参数不受赋值转换的影响.

JLS section 15.12.2.8

If any of the method’s type arguments were not inferred from the types of the actual arguments, they are now inferred as follows.

  • If the method result occurs in a context where it will be subject to assignment conversion (§5.2) to a type S, then let R be the declared result type of the method, and let R’ = R[T1 = B(T1) … Tn = B(Tn)] where B(Ti) is the type inferred for Ti in the previous section, or Ti if no type was inferred.

JLS不清楚为什么返回语句在这里计算.我能找到的最接近的是14.17

A return statement with an Expression must be contained in a method declaration that is declared to return a value (§8.4) or a compile-time error occurs. The Expression must denote a variable or value of some type T, or a compile-time error occurs. The type T must be assignable (§5.2) to the declared result type of the method, or a compile-time error occurs.

(如果第5.2节声明返回语句需要转换,那将是很好的.)

相关文章
相关标签/搜索