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

2020-08-22 03:21发布

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?

3条回答
何必那么认真
2楼-- · 2020-08-22 03:56

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.

查看更多
等我变得足够好
3楼-- · 2020-08-22 03:57

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

查看更多
ゆ 、 Hurt°
4楼-- · 2020-08-22 04:03

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.

查看更多
登录 后发表回答