Java无法弄清楚要调用的方法

标签 java

我还没有找到 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/

相关文章:

java - 在 OSX 10.5 上使用 LuaJava 的链接器错误

memory - 由于自定义启动器,设置 Java 应用程序的虚拟机最大内存而无需访问 VM 参数?

java - 如何确保文件写入失败时的文件完整性?

java - 无法从字符串创建 Path 对象

java - 如何用JPA映射实体?

java - Heroku 仅适用于刷新

java - Swing 布局管理器/解决方案来替换动态创建和嵌套的分割 Pane ?

java - Netbeans 的一个可能错误,它正在执行我更改的旧代码

java - PHP 开发人员关于 Java for Web Development 的问题

java - 使用混合 POJOS 处理集合,每个 POJO 使用不同的处理程序