public class Box<T> {
private T t;
public Box(T t){
this.t = t;
}
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
public static void main(String[] args) {
Box<Integer> b = new Box(new String("may be"));
System.out.println(b.get()); // successfully print out "may be"
System.out.println(b.get().getClass()); // error
}
}
Run Code Online (Sandbox Code Playgroud)
此代码给出了运行时错误:
exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
Run Code Online (Sandbox Code Playgroud)
b.get()不触发运行时错误?更确切地说:为什么编译器只在第二个checkcast字节码中插入指令(导致异常)? get()
在oracle的官方java文档Type Inference章节中,有一个这样的例子:
static <T> T pick(T a1, T a2) { return a2; }
Serializable s = pick("d", new ArrayList<String>());
Run Code Online (Sandbox Code Playgroud)
在这种情况下,类型参数是T但是传递了两种不同的类型,不应该a1的类型与a2相同吗?