java8增强了泛型方法的类型推断能力:允许通过调用方法的上下文推断类型参数的目标类型,允许在方法调用链中将推断到的泛型参数传递至最后一个方法。
class MyUtil<E>{
public static <Z> MyUtil<Z> nil(){
return null;
}
public static <Z> MyUtil<Z> cons(Z head,MyUtil<Z> tail){
return null;
}
E head(){
return null;
}
}
public class InferenceTest {
public static void main(String[] args) {
//通过方法赋值的目标参数来推断类型参数为String
MyUtil<String> ls=MyUtil.nil();
//通过cons()方法所以需要的参数类型来推断类型参数的类型为Integer
MyUtil.cons(42, MyUtil.nil());
}
}
京公网安备 11010502036488号