Java “static import” vs. “import static” in Java 8

2020-08-22 03:42发布

问题:

I was trying to use use static imports on Java, but I was writing it wrong

static import java.lang.System.out;

And the code compiled (although the "out" symbol couldn't be found), no syntax errors.

So, what does the "static import" actually means?

回答1:

This should not compile.

static import java.lang.System.out;

According to the JLS, a single static import should look like this:

import static java.lang.System.out;

All forms of the Java import statement start with the import keyword, and I don't think there is any other context (i.e. apart from an import statement) in which the import keyword can be used.

Note: the import and static keywords are not modifiers in this context, so the "modifiers can be supplied in any order" meta-rule does not apply here.


In short, either your compiler / IDE is broken or confused ... or what you are looking at is not real Java source code.



回答2:

Apparently, it was a bug.

I'm using Java 8 (JDK 1.8) from Sun, in order to test the lambdas... but I thought it was strange the "static import" to be accepted.

Thanks for all the answers. I'm gonna report this to Sun. :)



回答3:

In order to access static member of a class, you have to use the full class name that contains it. For example, to access the pi value in the Math class, you have to use java.lang.Math.PI. But, if you import it (import static java.lang.Math.PI), you can use just use PI in your code to access it.