50,545
社区成员
发帖
与我相关
我的任务
分享
public class Genericity{
public static void main(String[] args) {
A<Integer> a = new A();
Object o = a.show(); //没有报错,o得到一个字符串"123"
Object o2 = a.show().toString(); //报错,在toString之前加载了ClassLoader.java中的loadClass(),抛出ClassCastException
}
}
class A<E>{
E show(){
ArrayList arrayList = new ArrayList();
arrayList.add("123");
E o = (E)arrayList.get(0).toString(); //没有报错,强制转型也没有发生,o为字符串"123"
System.out.println(o);
return (E)arrayList.get(0);
}
}
public class Fanxing {
public static void main(String[] args) {
A<Integer> a = new A<Integer>();
Object o = a.show();
Object o2 =a.show().toString();
}
static class A<E>{
E show(){
return (E)"123";
}
}
}
反编译后的代码
public class Fanxing
{
public static void main(String[] args)
{
Fanxing.A a = new Fanxing.A();
Object o = a.show();
Object o2 = ((Integer)a.show()).toString();
}
static class A<E>
{
E show() {
return "123";
}
}
}