考虑以下简单的代码示例:
public class TestStaticImport {
static enum Branches {
APPLE,
IBM
}
public static void doSomething(Branches branch) {
if (branch == APPLE) {
System.out.println("Apple");
}
}
}
如果我们尝试编译这段代码,我们会得到错误信息:
java: cannot find symbol
symbol: variable APPLE
location: class TestStaticImport
这可以通过引入此枚举
的静态导入来解决:
导入静态
... TestStaticImport.Branches.*
但在这一刻,(对我而言)难以理解的事情开始了:
这个解决方案工作正常,一切都很好地编译,直到类 TestStaticImport
将被移动到空的根包中,即没有任何
package blablabla;
在这个 java 文件的顶部;
代码行:import static TestStaticImport.Branches.*;
在我的 Intellij IDEA 中突出显示为有效代码(IDE 的名称无关紧要,仅供引用),但是当我尝试编译时出现以下错误代码:
java: 包 TestStaticImport 不存在
那么,其实有两个问题:
1) 主要问题:为什么无法从空目录import static
?
2) 允许在代码中仅使用名称引用枚举字段的另一种方法(如果存在)是什么(即 APPLE
而不是 Branches.APPLE
),除了静态导入?
附言请不要告诉我,空包是丑陋的风格等等。这个问题只是理论上的问题。
最佳答案
Java language specification禁止从未命名的包中导入任何内容:
A type in an unnamed package (§7.4.2) has no canonical name, so the requirement for a canonical name in every kind of import declaration implies that (a) types in an unnamed package cannot be imported, and (b) static members of types in an unnamed package cannot be imported. As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time error on any attempt to import a type (or static member thereof) in an unnamed package.
关于java - 导入没有包名称的静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14258369/