作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
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
}
}
此代码给出运行时错误:
exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
b.get()
没有触发运行时错误?更准确地说:为什么编译器仅第二个 get() 将
(导致异常)? checkcast
指令插入字节码
最佳答案
请注意:
get()
的结果用于println(Object)
:换句话说:接收方需要一个 Object,并且“条件”将永远为真。作为背景,可以查看 Java 语言规范,第 5.52 章:
The cast is a checked cast.
Such a cast requires a run-time validity check. If the value at run time is null, then the cast is allowed. Otherwise, let R be the class of the object referred to by the run-time reference value, and let T be the erasure (§4.6) of the type named in the cast operator. A cast conversion must check, at run time, that the class R is assignment compatible with the type T, via the algorithm in §5.5.3.
分别是第5.53章Checked Casts at Run Time .
关于分配给泛型类型的 Java 原始类型值运行时 getClss() 方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45757141/
我是一名优秀的程序员,十分优秀!