用Java中的泛型类型安全 [英] Type safety with generics in Java
问题描述
我遇到了Java中的泛型行为,我完全无法理解(使用我的.NET背景)。
I've encountered a behaviour of generics in Java that I completely can't understand (with my .NET background).
public class TestGeneric<T>
{
public void get (Object arg)
{
T temp = (T) arg;
System.out.println(temp.toString());
return;
}
}
TestGeneric<Integer> tg = new TestGeneric<Integer>();
tg.get("Crack!!!");
请告诉我为什么我没有得到ClassCastException,而且在Idea中我看到temp为字符串
赋值后的值为Crack !!!
。另外,我怎么可能会抛出ClassCastException?我在Windows 7 x64上使用JDK 1.7.0_07。
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.
推荐答案
你没有得到类转换异常的原因是Java泛型通过类型擦除来实现。与需要对CLS进行重大更改的.NET泛型不同,Java泛型在编译时完全处理。在运行时,转换为 T
会被忽略。为了在运行时检查类型,您需要存储 Class< T>
,并使用它的方法来检查传入参数的类型:
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<T>
, and use its methods to check the type of a parameter passed in:
public class TestGeneric<T>
{
private Class<T> genClass;
public TestGeneric(Class<T> 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<Integer> tg = new TestGeneric<Integer>(Integer.class);
tg.get("Bang!!!"); // Now that's a real Bang!!!
这篇关于用Java中的泛型类型安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!