根据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