不会有任何 ClassCastException,除非你的 T 有一些基础:
public class GenericsTest
{
public static void main(String[] args)
{
System.out.println(cast(Integer.valueOf(0)));
System.out.println(GenericsTest.<Long> cast(Integer.valueOf(0)));
System.out.println(GenericsTest.<Long> cast("Hallo"));
System.out.println(castBaseNumber(Integer.valueOf(0)));
System.out.println(GenericsTest.<Long> castBaseNumber(Integer.valueOf(0)));
System.out.println(GenericsTest.<Long> castBaseNumber("Hallo"));
}
private static <T extends Number> T castBaseNumber(Object o)
{
T t = (T)o;
return t;
}
private static <T> T cast(Object o)
{
T t = (T)o;
return t;
}
}
在上面的示例中,前 5 次调用 cast 和 castBaseNumber 时不会出现 ClassCastException。只有第 6 次调用会引发 ClassCastException,因为编译器有效地将 cast() 转换为 return (Object) o,并将 castBaseNumber() 转换为 return (Number)o;。温你写
String s = GenericsTest.<Long> cast("Hallo");
你会得到一个 ClassCastException,但不是在 cast-method 中,而是在分配给 s 时。
因此,我确实认为,您的“T”不仅仅是“T”,而是“T extends Something”。所以你可以检查:
Object o = decoder.readObject();
if (o instanceof Something)
restoredItem = (T) o;
else
// Error handling
但这仍然会在以后使用类时导致错误。
public Reader<T extends Number>{...}
Long l = new Reader<Long>("file.xml").getValue(); // there might be the ClassCastException
对于这种情况,只有汤姆的建议可能会有所帮助。