java 不能`import static`静态嵌套类吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16595847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:24:56  来源:igfitidea点击:

Cannot `import static` static nested class?

javaimportcompilationstaticpackage

提问by Dog

I have a class Awith a static nested class inside it called B:

我有一个A包含静态嵌套类的类,称为B

import static A.B.*;

class A {
    static class B {
        static int x;
        static int y;
    }
    public static void main(String[] args) {
        System.out.println(x);
    }
}

I want to static import everything in B, but it wont work:

我想静态导入中的所有内容B,但它不起作用:

$ javac A.java
A.java:1: package A does not exist
import static A.B.*;
               ^
A.java:9: cannot find symbol
symbol  : variable x
location: class A
        System.out.println(x);
                           ^
2 errors

Why?

为什么?

回答by Reimeus

This won't work if Ais in the default package. However, you could add a package declaration:

如果A在默认包中,这将不起作用。但是,您可以添加包声明:

package mypackage;

and use

并使用

import static mypackage.A.B.*;

The static import syntax from from the JLSis given:

给出了来自JLS的静态导入语法:

SingleStaticImportDeclaration: import static TypeName. Identifier ;

SingleStaticImportDeclaration:导入静态TypeName。标识符;

where TypeNameis required to be full qualified.

其中TypeName需要是完全限定的

In Using Package Membersthe static importsyntax is given with package name included:

使用包成员中static import给出了包含包名称的语法:

import static mypackage.MyConstants.*;

It is recommendedto use staticimports very sparingly.

建议static非常谨慎地使用导入。

回答by Konstantin Yovkov

It should be

它应该是

import <the-package-for-the-class-A>.A.B.*;

If A is in the default package, this will fail.

如果 A 在默认包中,这将失败。

Last, it's not a good practice to import *. Just import only the things that you need, in this case - import static <the-package-for-the-class-A>.A.B.x;if you're gonna use only the xvariable.

最后,导入*. 在这种情况下,只需导入您需要的东西 -import static <the-package-for-the-class-A>.A.B.x;如果您只使用x变量。