如何在不指定其类型的情况下引用我的 Java Enum
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1677037/
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
How can I reference my Java Enum without specifying its type
提问by Bill K
I have a class that defines its own enum like this:
我有一个像这样定义自己的枚举的类:
public class Test
{
enum MyEnum{E1, E2};
public static void aTestMethod() {
Test2(E1); // << Gives "E1 cannot be resolved" in eclipse.
}
public Test2(MyEnum e) {}
}
If I specify MyEnum.E1 it works fine, but I'd really just like to have it as "E1". Any idea how I can accomplish this, or does it have to be defined in another file for this to work?
如果我指定 MyEnum.E1 它工作正常,但我真的只是想把它作为“E1”。知道我如何实现这一点,还是必须在另一个文件中定义它才能工作?
CONCLUSION: I hadn't been able to get the syntax for the import correct. Since several answers suggested this was possible, I'm going to select the one that gave me the syntax I needed and upvote the others.
结论:我无法获得正确的导入语法。由于有几个答案表明这是可能的,我将选择一个提供了我需要的语法的答案,然后对其他答案投赞成票。
By the way, a REALLY STRANGE part of this (before I got the static import to work), a switch statement I'd written that used the enum did not allow the enum to be prefixed by its type--all the rest of the code required it. Hurt my head.
顺便说一句,这是一个非常奇怪的部分(在我让静态导入工作之前),我编写的使用枚举的 switch 语句不允许枚举以其类型作为前缀 - 所有其余的代码需要它。伤了我的头。
采纳答案by Pascal Thivent
Actually, you can do a static importof a nested enum. The code below compiles fine:
实际上,您可以对嵌套枚举进行静态导入。下面的代码编译得很好:
package mypackage;
import static mypackage.Test.MyEnum.*;
public class Test
{
enum MyEnum{E1, E2};
public static void aTestMethod() {
Test2(E1);
}
public static void Test2(MyEnum e) {}
}
回答by Yishai
You can do a static import on a nested class:
您可以对嵌套类进行静态导入:
import static apackage.Test.Enum.*;
回答by Jayen
The Test class has to be defined in a package to be importable.
Test 类必须在包中定义才能导入。
With package defined in Test
(IT WORKS):
使用Test
(IT WORKS)中定义的包:
package mypackage;
You can use:
您可以使用:
import static mypackage.Test.MyEnum.*;
Without package defined, you cannot use (DOES NOT WORK):
没有定义包,你不能使用(不工作):
import static Test.MyEnum.*;