0

Could someone explain why the first cast does not give a CCE ?

public class Test {

  public static void main(String[] args) throws Throwable {
    Test.<RuntimeException>throwIt(new Exception());
  }

  @SuppressWarnings("unchecked")
  private static <T extends Throwable> void throwIt(Throwable throwable) throws T {
    throw (T) throwable; // no ClassCastException
    throw (RuntimeException) throwable; // ClassCastException(as it should be)
  }
}

P.S. Comment one cast (otherwise it won't compile).

4

1 回答 1

1

这是 Java 泛型实现的特点,它是通过类型擦除实现的,这就是为什么 (T) cast 实际上将它转换为 Throwable 作为最左边界。因为, new Exception() 产生一个 Throwable 对象,您可以安全地抛出它。

您可以在 JSL http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#108979中检查它

于 2013-02-27T12:25:50.853 回答