简体   繁体   English

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

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

Consider the following two simple java code snippets:考虑以下两个简单的 java 代码片段:

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

This works fine.这工作正常。 But if I use toString a lot, I may be tempted to use a static import, like so:但如果我经常使用 toString,我可能会想使用 static 导入,如下所示:

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

If I try this, Java thinks I'm trying to call the toString() from Object, and then complains that toString takes no arguments.如果我尝试这个,Java 认为我正在尝试从 Object 调用 toString(),然后抱怨 toString 不接受 arguments。 This seems silly: I'm in a static method, so that toString shouldn't even be considered.这似乎很愚蠢:我使用的是 static 方法,因此甚至不应该考虑 toString。 (Even in an instance method, I feel that Java should get the right answer here.) (即使在实例方法中,我觉得 Java 应该在这里得到正确的答案。)

Is there any way I can fix this, or do static imports just not work if that name is already "taken"?有什么办法可以解决这个问题,或者如果该名称已经“采用”,static 导入是否不起作用?

No, there's no way round this.不,没有办法解决这个问题。

[From JLS 15.12, Method Invocation Expressions] ( https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.12 ) (more specifically from 15.12.1, "Determine Class or Interface to Search") [来自 JLS 15.12,方法调用表达式]( https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.12 )“。 Class 或搜索接口")

  • If the form is MethodName, that is, just an Identifier, then:如果form是MethodName,也就是只是一个Identifier,那么:

    If the Identifier appears in the scope of a method declaration with that name (§6.3, §6.4.1), then:如果标识符出现在具有该名称的方法声明的 scope 中(第 6.3 节、第 6.4.1 节),则:

    • If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration.如果存在该方法是其成员的封闭类型声明,则令 T 为最里面的此类类型声明。 The class or interface to search is T. class 或搜索接口是 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.它有效地在嵌套类的超类层次结构中查找方法,然后在封闭的 class 及其超类层次结构中查找方法。 See §6.5.7.1 for an example.有关示例,请参见第 6.5.7.1 节。

    • Otherwise, the method declaration may be in scope due to one or more single-static-import or static-import-on-demand declarations.否则,由于一个或多个单静态导入或按需静态导入声明,方法声明可能在 scope 中。 There is no class or interface to search, as the method to be invoked is determined later (§15.12.2.1).没有 class 或搜索接口,因为要调用的方法稍后确定(第 15.12.2.1 节)。

So, the "local" method will always be matched before the static import.因此,“本地”方法将始终在 static 导入之前匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM