简体   繁体   中英

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

Consider the following two simple java code snippets:

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:

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. This seems silly: I'm in a static method, so that toString shouldn't even be considered. (Even in an instance method, I feel that Java should get the right answer here.)

Is there any way I can fix this, or do static imports just not work if that name is already "taken"?

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")

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

So, the "local" method will always be matched before the static import.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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