java中为什么不能强制转换_为什么Java中的强制转换异常致命?

根据this文章:

In contrast to static type checking, dynamic type checking may cause a program to fail at runtime due to type errors. In some programming languages, it is possible to anticipate and recover from these failures – either by error handling or poor type safety. In others, type checking errors are considered fatal.

Java是一个类型检查错误致命的例子.为什么Java(也许是大多数静态类型语言)如此严格以至于在发生类型错误时它在运行时失败?假设您将对象A(实际类型为int)转换为Object类型,并向下转换为String.编译时检查将通过,但运行时类型检查将失败并发生致命异常.这似乎很苛刻,因为它不像非法的ArgumentException,程序字面上无法继续(无效的演员会失去类型安全但不应该是不可能的).在我看来,最好的情况是抛出一个警告然后在尝试调用整数对象上的String方法indexOf时致命地失败.在尝试执行此无效转换时,Java是否有理由无法在运行时继续运行?

解决方法:

Java is an example where type checking errors are fatal.

不,不是.你可以抓住它们.

Why is Java (and maybe most static typed languages) so strict that it fails at runtime if a type error occurs?

因为这就是“静态打字”的意思;同上’严格打字’.

Let’s say you upcast object A (actual type int) to type Object, and downcast to String. Compile-time checking will pass, but the runtime type check will fail with a fatal exception.

不,不会.它会因未经检查的RuntimeException而失败.

This seems harsh, as it’s not like an illegalArgumentException where the program literally cannot proceed (an invalid cast loses type safety but shouldn’t be impossible).

但这是不可能的.演员无法进行.生成目标代码的方式假设如此.

It would seem to me like the most optimal situation would be to throw a warning

它抛出一个RuntimeException.

and then fail fatally if trying to call, say, String method indexOf on the integer object.

好吧,它没有那样做.

Is there a reason for Java actually failing to proceed at runtime when trying to perform this invalid cast?

该实现是围绕异常发生的事实设计的.

标签:java,oop

来源: https://codeday.me/bug/20190724/1526125.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值