我有一个通用方法
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/