假设我有一个通用类Parcel和一个通用方法,如下面的代码所示.该方法打印并返回x,该方法在方法内分配了一个类型参数Integer.
public class Parcel<T> {
public <X> X deliver(){
X x = (X) new Integer(100);
System.out.println(x);
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
在main中,我通过传递一个类型参数Parcel来调用方法.但它仍然打印100.
public static void main(String args[]) {
Parcel<String> parcel = new Parcel<>();
System.out.println(parcel.<Parcel> deliver());
}
Run Code Online (Sandbox Code Playgroud)
接下来,在打印行中传递的类型参数Parcel不起任何作用,我在此预期会有异常.它是如何工作的 ?