gpt4 book ai didi

java.lang.ClassCastException 编译时检查本来可以用更好的方式处理

转载 作者:行者123 更新时间:2023-11-29 08:34:33 25 4
gpt4 key购买 nike

我有两个父类和子类,在运行时发生 clascastexception对于下面给出的代码。

从下面的代码可以明显看出会有classcastexception。我认为 java 可以用更好的方式处理,以便在下面的情况下它可能会给出编译时错误。

我还有其他原因导致 java 在编译期间没有给出错误。只想知道我是否遗漏了什么。

public class ClassCastExcp {

public static void main(String args[]){
Child chd = (Child) new Parent(); //it will force you to cast and gives classcastexception in runtime
}

}

class Parent{
}

class Child extends Parent{
}

最佳答案

根据您所写的内容,我认为您已经完全理解为什么会出现运行时异常。 (如果不是,请参阅其他答案。)

Is there any reason that java is not giving error during compile time. Just want to know if anything I am missing.

它不会给出编译错误,因为根据 JLS,该代码是合法的 Java。 (有关更多详细信息,请参阅@ajb 的回答,但真正的解释在 JLS 本身中。)兼容的 Java 编译器需要接受这个......至少在“兼容”模式下。

现在,Java 编译器可以报告类似这样的警告,也可以将警告升级为错误。然而:

  • 这个特殊示例在实际代码中不太可能出现。编译器编写者通常不会为很少发生的错误实现警告。

  • 任何实现 Java 编译器并默认处理此类错误的人都会受到必须处理其他人/组织编写的代码的用户的强烈批评。

关于java.lang.ClassCastException 编译时检查本来可以用更好的方式处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com