gpt4 book ai didi

java - 如何对 java.util.Arrays.toString 使用静态导入?

转载 作者:行者123 更新时间:2023-12-02 10:41:49 27 4
gpt4 key购买 nike

考虑以下两个简单的 java 代码片段:

import java.util.Arrays;
class Okay {
public static void main(String... args) {
System.out.println(Arrays.toString(new int[0]));
}
}

这工作正常。但如果我经常使用 toString,我可能会想使用静态导入,如下所示:
import static java.util.Arrays.toString;
class DoesNotCompile {
public static void main(String... args) {
System.out.println(toString(new int[0]));
}
}

如果我尝试这个,Java 认为我正在尝试从 Object 调用 toString(),然后提示 toString 不接受任何参数。这似乎很愚蠢:我在一个静态方法中,所以 toString 甚至不应该被考虑。 (即使在实例方法中,我觉得Java应该在这里得到正确的答案。)

有什么办法可以解决这个问题,或者如果该名称已被“采用”,则静态导入不起作用?

最佳答案

不,没有办法解决这个问题。
[来自 JLS 15.12,方法调用表达式] (https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.12)(更具体地说,来自 15.12.1,“确定要搜索的类或接口(interface)”)

  • If the form is MethodName, that is, just an Identifier, then:

    If the Identifier appears in the scope of a method declaration with that name (§6.3, §6.4.1), then:

    • 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.

      This search policy is called the "comb rule". It effectively looks for methods in a nested class's superclass hierarchy before looking for methods in an enclosing class and its superclass hierarchy. See §6.5.7.1 for an example.

    • Otherwise, the method declaration may be in scope due to one or more single-static-import or static-import-on-demand declarations. There is no class or interface to search, as the method to be invoked is determined later (§15.12.2.1).


因此,“本地”方法将始终在静态导入之前匹配。

关于java - 如何对 java.util.Arrays.toString 使用静态导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61600571/

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