我还没有找到 java 编译器无法在以下程序中选择合适的方法来执行的原因(in JLS):
public class UpperLevelClass {
private static String getStringanotherNameMethod(String a, String b) {
return null;
}
private static String firstSignatureMethod(String a, String b) {
return null;
}
static class StaticNestedClass extends UpperLevelClass{
public void getStringfirstNameMethod(String a, Integer b) {
getStringanotherNameMethod("test", "fff");//compiles
firstNameMethod("test", "fff");//error below
}
}
}
编译结束,出现以下错误:
error: method firstNameMethod in class StaticNestedClass cannot be applied to given types;
firstNameMethod("test", "fff");
^
required: String,Integer
found: String,String
reason: argument mismatch; String cannot be converted to Integer
添加一些历史:
起初,我有几个static
方法,在上层调用中使用default
访问,并且everething 编译和运行(从静态嵌套类)很好。然后,static
方法访问权限更改为 private
,由于一个方法(在本例中为 firstNameMethod)中的错误,programm 停止编译,但其他方法编译正常。
我已经尝试(感谢@ Jorn Vernee)在 Eclipse 中编译和运行程序,它编译并运行。
最佳答案
搜索合适的方法是一个两步过程。
第 1 步涉及选择要搜索的类别。本步骤JLS的相关行:
If the Identifier appears in the scope of a visible method declaration with that name:
If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or interface to search is T.
请注意,这里说的是Identifier 而不是Signature。这意味着它在此阶段只查看方法名称,而不是参数。因为 StaticNestedClass
包含一个名为 getString
的方法,这就是要搜索的类。
只有当我们到达第 2 步时,参数才会被考虑在内。由于StaticNestedClass
中没有getString
方法调用兼容,导致编译失败。
关于Java无法弄清楚要调用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53364899/