Java异常。将一种类型转换为另一种类型

Java异常。将一种类型转换为另一种类型,java,exception,exception-handling,Java,Exception,Exception Handling,有人能解释为什么第一组演员没有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 th

有人能解释为什么第一组演员没有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)
  }
}
公共类测试{
公共静态void main(字符串[]args)抛出可丢弃的{
Test.throwIt(新异常());
}
@抑制警告(“未选中”)
私有静态void throwIt(Throwable-Throwable)抛出T{
throw(T)throwable;//无ClassCastException
throw(RuntimeException)throwable;//ClassCastException(按原样)
}
}

注释一个cast(否则它将无法编译)。

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

您可以在JSL中检查它

第二个
抛出的
无法到达您的问题是什么?你的代码正在编译吗?您将获得无法访问的代码编译错误。哦,常见,注释一,然后另一个异常是超类,您无法将其强制转换为RuntimeException。我可以告诉您,编译代码时,泛型参数类型将被删除。在运行时,甚至没有强制转换。在我找到相应的JLS部分来验证为什么这是有效的行为之前,我不会发布答案。