java - 这是java中的类型推断吗?

标签 java type-inference

我有一个通用方法

public <K extends Number> K get()
{
    ...
}

当我调用这个方法时,我使用如下语法:

Integer i = instance.<Integer>get();

但是,这也是合法的:

Integer i = instance.get();

我的问题是,第二种方法调用是 Java 中的一种类型推断形式吗?

最佳答案

是的,这是基于赋值类型的类型推断。它在 section 15.12.2.8 中指定JLS 的:

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.

Then, a set of initial constraints consisting of:

  • the constraint S >> R', provided R is not void; and
  • additional constraints Bi[T1 = B(T1) ... Tn = B(Tn)] >> Ti, where Bi is the declared bound of Ti,

is created and used to infer constraints on the type arguments using the algorithm of section (§15.12.2.7). Any equality constraints are resolved, and then, for each remaining constraint of the form Ti <: Uk, the argument Ti is inferred to be glb(U1, ..., Uk) (§5.1.10).

关于java - 这是java中的类型推断吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6290778/

相关文章:

java - 验证来自已签名 jar 的 http 请求

java - 在tomcat上获取变量的描述

java - Spring 批处理 : Reading data from one source but writing different data to 2 separate files

c# - 为什么类型推断和隐式运算符在以下情况下不起作用?

java - 从另一个 jar 读取变量值

java - Android 后退按钮无法正常使用

c# - 将类型推断与流畅的接口(interface)结合使用

scala - 为什么 Scala 类型与预期的 Int 不匹配?

Haskell:读取并输入签名

c# - 匹配任何 IEnumerable<T> 的通用类型参数