java的泛型是类型安全,用Java中的泛型类型安全

I've encountered a behaviour of generics in Java that I completely can't understand (with my .NET background).

public class TestGeneric

{

public void get (Object arg)

{

T temp = (T) arg;

System.out.println(temp.toString());

return;

}

}

TestGeneric tg = new TestGeneric();

tg.get("Crack!!!");

Please tell me why I'm not getting ClassCastException in get, moreover, in Idea I see temp as String after assignment and having value of "Crack!!!". Also, how could I have that ClassCastException throwed? I'm using JDK 1.7.0_07 on Windows 7 x64.

解决方案

The reason you are not getting a class cast exception is that Java generics are implemented through type erasure. Unlike .NET generics that required significant changes to CLS, Java generics are processed entirely in compile-time. At runtime, the cast to T is ignored. In order to check type at runtime, you need to store Class, and use its methods to check the type of a parameter passed in:

public class TestGeneric

{

private Class genClass;

public TestGeneric(Class t) {genClass = t;}

public void get (Object arg)

{

if (!genClass.isInstance(arg)) {

throw new ClassCastException();

}

T temp = (T) arg;

System.out.println(temp.toString());

return;

}

}

TestGeneric tg = new TestGeneric(Integer.class);

tg.get("Bang!!!"); // Now that's a real Bang!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值