导入静态没有包名称 [英] import static without package name

查看:132
本文介绍了导入静态没有包名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简单的代码示例:

Consider the following simple example of code:

public class TestStaticImport {
    static enum Branches {
        APPLE,
        IBM
    }
    public static void doSomething(Branches branch) {
        if (branch == APPLE) {
            System.out.println("Apple");
        }
    }
}

如果我们尝试编译这段代码,我们将收到错误消息:

If we will try to compile this code, we will get the error message:

java: cannot find symbol
  symbol:   variable APPLE
  location: class TestStaticImport

这可以通过引入静态导入来解决这个 enum

This could be solved by introducing static import of this enum:

import static ... TestStaticImport.Branches。*

但是在这一刻不可理解的事情(对我来说)开始:

这个解决方案工作正常,一切都编译得很好,直到class TestStaticImport 将被移动到空的root包中,即在这个java文件的顶部没有任何

this solution works fine, everything is well compiled, until class TestStaticImport will be moved into empty root package, i.e. there isn't any

包blablabla; ;

代码行: import static TestStaticImport.Branches。*; 在我的Intellij IDEA中突出显示为有效代码(IDE doe的名称) sn't matter,仅供参考),但当我尝试编译此类代码时出现以下错误:

Code line: import static TestStaticImport.Branches.*; is highlighted as valid code in my Intellij IDEA (name of IDE doesn't matter, just for information), but when I try to compile such code following error appears:

java:package TestStaticImport不存在

所以,实际上有两个问题:

So, there are actually two questions:

1)主要问题:为什么从空目录导入静态是不可能的?

1) Main question: why is it impossible to import static from empty directory?

2)什么是另一种方式(如果存在)允许仅使用其名称来代码引用枚举的字段(即 APPLE 而不是 Branches.APPLE ),静态导入除外?

2) What is another way (if it exists) for allowing in code references to enum's fields using just their names (i.e. APPLE instead of Branches.APPLE), except static import?

PS请不要告诉我,空包装是丑陋的样式等等。这个问题只是理论上的问题。

P.S. Please, don't tell me, that empty packages is ugly style and so on. This question is just theoretical problem.

推荐答案

Java语言规范禁止从未命名的包中导入任何内容:

The Java language specification forbids any imports from the unnamed package:


未命名包中的类型(第7.4.2节)没有规范名称,因此每种导入声明
中规范名称的
要求意味着(a)类型无法导入未命名的包中,并且无法导入
(b)未命名包中类型的静态成员。
因此,§7.5.1,§7.5.2,§7.5.3和§7.5.4都要求在导入类型(或其静态成员)的任何尝试时出现编译时
错误)在
未命名的包中。

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.

这篇关于导入静态没有包名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆