Java "static import" versus "import static" in Java 8

I tried using static import in Java, but I wrote incorrectly

static import java.lang.System.out; 

And the code compiled (although the "out" symbol was not found), no syntax errors.

So what does “static import” mean?

+7
source share
3 answers

This should not compile.

 static import java.lang.System.out; 

According to JLS, one static import should look like this:

 import static java.lang.System.out; 

All forms of the Java import statement begin with the import keyword, and I don’t think there is any other context (that is, besides the import statement) in which you can use the import keyword.

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


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

+19
source

Apparently, this was a mistake.

I use Sun's Java 8 (JDK 1.8) to test lambdas ... but I thought it was strange to accept "static imports".

Thanks for all the answers. I am going to report this to the Sun. :)

+3
source

To access a static member of a class, you must use the fully qualified name of the class that contains it. For example, to access the pi value in the Math class, you must 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 to it.

0
source

All Articles