javac (java编译器)如何发现与歧义相关的错误,并在编译时本身生成错误?
编译器如何在执行前发现我们正在传递一个空值
public class Ambiguity {
public static void main(String[] args) {
Ambiguity test = new Ambiguity();
test.overloadedMethod(null);
}
void overloadedMethod(IOException e) {
System.out.println("1");
}
void overloadedMethod(FileNotFoundException e) {
System.out.println("2");
}
void overloadedMethod(Exception e) {
System.out.println("3");
}
void overloadedMethod(ArithmeticException e) {
System.out.println("4");
}
}发布于 2022-09-21 10:04:59
问题不在于编译器知道您正在传递null;关键是当您在代码中编写文字null时,编译器不知道该null的类型,因此它不知道要调用哪种重载。
例如,这将很好地编译:
FileNotFoundException e = null;
test.overloadedMethod(e);还可以使用显式强制转换来指示您想要的类型:
test.overloadedMethod((FileNotFoundException) null);请记住,重载是在编译时解决的。因此,如果您调用test.overloadedMethod(e),其中e是静态类型的Exception,那么即使e在运行时是FileNotFoundException,它也总是调用overloadedMethod(Exception)。
https://stackoverflow.com/questions/73798811
复制相似问题