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

How to use a static import for java.util.Arrays.toString?

考虑以下两个简单的 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这里应该可以得到正确答案。)

有什么办法可以解决这个问题,或者如果该名称已经是 "taken",静态导入就不起作用了?

不,没有办法解决这个问题。

[来自 JLS 15.12,方法调用表达式] (https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.12)(更具体地说来自 15.12.1,“确定 Class 或搜索接口”)

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

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